📓 Python Programming - Introduction to Python


1. What exactly is Python?

Python is a high-level, interpreted, general-purpose programming language known for its simplicity and readability.

It is widely used for:

  • Web Development

  • Data Science

  • Machine Learning & AI

  • Automation & Scripting

  • Software Development

  • Game Development

Key Features:

  • Easy to learn & use

  • Open-source & community-driven

  • Extensive libraries & frameworks

  • Cross-platform

  • Supports multiple programming paradigms (procedural, object-oriented, functional)

2. Python's Root and Ecosystem

🐍 Origin:

  • Created by Guido van Rossum in the late 1980s.

  • First released in 1991.

  • Name inspired by the British comedy group Monty Python, not the snake.

🌍 Ecosystem:

  • Rich set of libraries (e.g., NumPy, Pandas, Matplotlib)

  • Package management through pip

  • Large developer community

  • Popular frameworks: Django, Flask, FastAPI for web; TensorFlow, PyTorch for AI/ML

3. Python Installation & IDEs Setting Up

⚙️ Installation: - Recommended: Install latest version from https://www.python.org

💻 Popular IDEs for Python:

  • Google Colab (cloud-based, no installation needed)

  • Jupyter Notebook (ideal for data science, interactive coding)

  • VS Code (lightweight, customizable)

  • PyCharm (feature-rich, professional-grade)

➤ Example: Running Python in Google Colab 1. Visit https://colab.research.google.com

  1. Click "New Notebook"

  2. Write your Python code and press Shift + Enter to run

# Simple Python code in Colab

print("Step 1: Write code. Step 2: Debug. Step 3: Cry. Repeat.")
Step 1: Write code. Step 2: Debug. Step 3: Cry. Repeat.

4. Python Framework & Syntax

Python Syntax Basics: - Case-sensitive

  • Indentation defines blocks (no curly braces)

  • Easy to read and write

# Printing a message
print("I thought Python was a snake... why am I coding?")

# Indentation defines code blocks
x = 10
if x > 5:
    print("x is greater than 5")
I thought Python was a snake... why am I coding?
x is greater than 5
# Variables and Data Types
name = "Chirag"        # String
age = 25               # Integer
height = 5.6           # Float
is_student = True      # Boolean

print(f"Name: {name}, Age: {age}, Height: {height}, Student: {is_student}")

# Comments in Python
# This is a single-line comment

"""
This is a multi-line comment
or docstring
"""

# Python's dynamic typing
x = 10        # x is an integer
x = "hello"   # now x is a string
x = [1, 2, 3] # now x is a list
print("Dynamic typing demo:", x)
Name: Chirag, Age: 25, Height: 5.6, Student: True
Dynamic typing demo: [1, 2, 3]
import cowsay

cowsay.kitty("I am a kitty! not a snake!")
  __________________________
| I am a kitty! not a snake! |
  ==========================
                             \
                              \
                               \
                                \
                                 ("`-'  '-/") .___..--' ' "`-._
                                  ` *_ *  )    `-.   (      ) .`-.__. `)
                                   (_Y_.) ' ._   )   `._` ;  `` -. .-'
                                _.. `--'_..-_/   /--' _ .' ,4
                               ( i l ),-''  ( l i),'  ( ( ! .-'

Let's try basic operations:

  • Printing messages

  • Simple arithmetic

  • Using variables

# Print statement
print("Python: Less hiss, more code.")

# Arithmetic operations
a = 5
b = 3
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Division:", a / b)
Python: Less hiss, more code.
Sum: 8
Difference: 2
Product: 15
Division: 1.6666666666666667
# Getting user input
# name = input("What's your name? ")
# age = input("How old are you? ")
# print(f"Hello {name}! You are {age} years old.")

# Note: Uncomment the above lines to try interactive input

# String operations
message = "Python Programming"
print("Original:", message)
print("Uppercase:", message.upper())
print("Lowercase:", message.lower())
print("Length:", len(message))
print("Replace:", message.replace("Python", "Amazing Python"))
Original: Python Programming
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Length: 18
Replace: Amazing Python Programming
  • Python is simple, versatile, and powerful

  • Created by Guido van Rossum

  • Strong ecosystem with packages & frameworks

  • Available in multiple IDEs (Colab, Jupyter, VS Code)

  • Indentation is critical in Python

  • Hands-on coding encouraged

5. The Zen of Python & Best Practices

🧘 Python Philosophy: Python follows the "Zen of Python" principles - try running import this in Python!

# The Zen of Python
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

📋 Python Naming Conventions:

  • Variables: snake_case (e.g., user_name, total_count)

  • Functions: snake_case (e.g., calculate_area(), get_user_input())

  • Classes: PascalCase (e.g., UserAccount, DataProcessor)

  • Constants: UPPER_CASE (e.g., MAX_SIZE, DEFAULT_TIMEOUT)

# Basic Error Handling
try:
    number = int("not_a_number")
except ValueError as e:
    print(f"Oops! That's not a valid number: {e}")

# Better approach
try:
    user_input = "42"  # This would normally be input()
    number = int(user_input)
    result = 100 / number
    print(f"Result: {result}")
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Something went wrong: {e}")
Oops! That's not a valid number: invalid literal for int() with base 10: 'not_a_number'
Result: 2.380952380952381

📝 Practice Exercises

Basic Exercises:

  1. Print your name using Python.

  2. Try basic arithmetic operations (addition, subtraction, multiplication, division).

  3. Explore Google Colab or Jupyter Notebook and run your first Python code.

Intermediate Exercises:

  1. Create variables for your name, age, and favorite color, then print them in a formatted sentence.

  2. Write a program that calculates the area of a rectangle (length × width).

  3. Try the import this command and read through the Zen of Python.

Challenge Exercises:

  1. Create a simple calculator that adds two numbers (use variables, not input for now).

  2. Write a program that converts temperature from Celsius to Fahrenheit using the formula: F = (C × 9/5) + 32.

  3. Practice string operations: take a sentence and print it in uppercase, lowercase, and count its characters.