Why Python?
Python is the go-to language for beginners and professionals alike. It reads almost like English, has an enormous ecosystem of libraries, and is used across every domain of technology.
Web Development
Django, Flask, FastAPI
AI & Machine Learning
TensorFlow, PyTorch, scikit-learn
Data Science
Pandas, NumPy, Matplotlib
Automation
Scripting, DevOps, web scraping
Your First Program
The classic first step — let's print something to the screen:
# Your very first Python program!
print("Hello, World!")
How to run Python: Install Python from python.org, then open a terminal and type python3 filename.py. You can also use the interactive shell by just typing python3.
Python's Philosophy
Python has a set of guiding principles known as "The Zen of Python." Here are the key ones:
✨ Core Principles
Beautiful is better than ugly. — Write clean, readable code.
Simple is better than complex. — Don't over-engineer.
Readability counts. — Code is read more than it's written.
There should be one obvious way to do it. — Pythonic patterns exist for a reason.
How Python Runs Code
Python is interpreted, not compiled. This means you can run code line-by-line in the interactive shell — great for learning and experimenting!
Comments
# This is a single-line comment
"""
This is a multi-line comment
(technically a docstring).
Great for longer explanations.
"""
print("Comments are ignored by Python") # inline comment
🧠 Quick Check
Which function is used to display output in Python?
Creating Variables
In Python, you don't need to declare types. Just assign a value and Python figures it out:
# Python infers the type automatically
name = "Alice" # str (string)
age = 25 # int (integer)
height = 5.7 # float (decimal)
is_student = True # bool (boolean)
print(name, age, height, is_student)
Core Data Types
| Type | Example | Description |
|---|---|---|
int | 42, -7, 0 | Whole numbers (no limit in size!) |
float | 3.14, -0.5 | Decimal numbers |
str | "hello", 'world' | Text — single or double quotes |
bool | True, False | Boolean — always capitalized |
NoneType | None | Represents "nothing" or "no value" |
Checking & Converting Types
x = "42"
print(type(x)) # <class 'str'>
x = int(x) # Convert string to int
print(type(x)) # <class 'int'>
print(x + 8) # 50
# Other conversions
float("3.14") # 3.14
str(100) # "100"
bool(0) # False (0 is falsy)
bool(1) # True (non-zero is truthy)
Variable Naming Rules
📏 Rules & Conventions
Must start with a letter or underscore: name, _private ✅
Cannot start with a number: 2name ❌
Can contain letters, numbers, underscores: user_age_2 ✅
Case-sensitive: Name and name are different
Convention: Use snake_case for variables and functions: first_name
Avoid reserved words as variable names: if, for, class, return, import, True, False, None, etc.
Multiple Assignment
# Assign multiple variables at once
a, b, c = 1, 2, 3
# Swap values (no temp variable needed!)
a, b = b, a
print(a, b) # 2 1
Variable Creation
Create a variable called price set to 19.99 and a variable called item set to "notebook". Then print both.
Creating Strings
single = 'Hello'
double = "World"
multi = """This is a
multi-line string"""
# String concatenation
full = single + " " + double
print(full) # Hello World
f-Strings (Formatted Strings)
The modern, preferred way to embed variables in strings (Python 3.6+):
name = "Alice"
age = 25
# f-string — note the f before the quote
message = f"My name is {name} and I am {age} years old."
print(message)
# You can put expressions inside {}
print(f"Next year I'll be {age + 1}")
print(f"Name uppercase: {name.upper()}")
Next year I'll be 26
Name uppercase: ALICE
String Indexing & Slicing
s = "Python"
print(s[0]) # P (first character)
print(s[-1]) # n (last character)
print(s[0:3]) # Pyt (index 0,1,2 — end is exclusive)
print(s[2:]) # thon (from index 2 to end)
print(s[::2]) # Pto (every 2nd character)
print(s[::-1]) # nohtyP (reversed!)
Essential String Methods
| Method | Example | Result |
|---|---|---|
.upper() | "hello".upper() | "HELLO" |
.lower() | "HELLO".lower() | "hello" |
.strip() | " hi ".strip() | "hi" |
.replace() | "cat".replace("c","b") | "bat" |
.split() | "a,b,c".split(",") | ['a','b','c'] |
.join() | "-".join(["a","b"]) | "a-b" |
.startswith() | "hello".startswith("he") | True |
.find() | "hello".find("ll") | 2 |
len() | len("hello") | 5 |
Strings are immutable! Methods like .upper() return a new string — they don't change the original. You need to reassign: s = s.upper()
Reverse a String
Given word = "python", print it reversed using slicing.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3.333... |
// | Floor Division | 10 // 3 | 3 |
% | Modulus | 10 % 3 | 1 |
** | Exponent | 2 ** 10 | 1024 |
Comparison Operators
print(5 == 5) # True (equal)
print(5 != 3) # True (not equal)
print(5 > 3) # True (greater than)
print(5 <= 5) # True (less than or equal)
Logical Operators
x = 15
print(x > 10 and x < 20) # True (both true)
print(x > 20 or x < 5) # False (neither true)
print(not (x > 20)) # True (negation)
User Input
# input() always returns a string!
name = input("What's your name? ")
print(f"Hello, {name}!")
# Convert to number for math
age = int(input("Enter your age: "))
print(f"You'll be {age + 1} next year!")
Common Bug: Forgetting to convert input() to int() or float() before doing math. "5" + "3" gives "53" (concatenation), not 8!
Simple Calculator
Write code that takes two numbers and prints their sum. Use input() and int().
if / elif / else
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Indentation matters! Python uses indentation (4 spaces) to define code blocks — not curly braces. Wrong indentation = error.
Ternary (One-Line If)
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
Truthy & Falsy Values
⚡ What evaluates to False?
False, 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), None
Everything else is truthy — including "0", [0], negative numbers.
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty!") # This runs
Even or Odd?
Write code that checks if a number is even or odd using the modulus operator %.
for Loop
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop with range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8 (start, stop, step)
print(i)
# enumerate() — get index AND value
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
while Loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # Don't forget this — or infinite loop!
break, continue, else
# break — exit loop immediately
for i in range(10):
if i == 5:
break
print(i) # prints 0, 1, 2, 3, 4
# continue — skip this iteration
for i in range(5):
if i == 2:
continue
print(i) # prints 0, 1, 3, 4 (skips 2)
List Comprehensions
A powerful, Pythonic way to create lists in one line:
# Traditional way
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension — same result, one line!
squares = [x ** 2 for x in range(10)]
# With a filter
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
FizzBuzz
Print numbers 1-20. For multiples of 3 print "Fizz", multiples of 5 print "Buzz", both print "FizzBuzz".
Lists
Ordered, mutable (changeable) collections that can hold any type:
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Accessing elements (same as strings)
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']
List Methods
fruits = ["apple", "banana"]
fruits.append("cherry") # Add to end
fruits.insert(1, "blueberry") # Add at index 1
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove & return last
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
print(len(fruits)) # Length
print("apple" in fruits) # True (membership test)
Tuples
Like lists, but immutable (cannot be changed after creation). Use for data that shouldn't change.
point = (10, 20)
rgb = (255, 128, 0)
print(point[0]) # 10
# Tuple unpacking
x, y = point
print(x, y) # 10 20
# point[0] = 5 # ❌ TypeError! Tuples are immutable
📊 List vs Tuple
List [ ] — Mutable, use when data will change (shopping cart, to-dos)
Tuple ( ) — Immutable, use for fixed data (coordinates, RGB colors, DB records)
Dictionaries
Store data as key: value pairs. Lightning-fast lookups.
person = {
"name": "Alice",
"age": 25,
"city": "Mumbai"
}
# Access values
print(person["name"]) # Alice
print(person.get("age")) # 25 (safer — returns None if missing)
# Modify
person["age"] = 26 # Update
person["email"] = "a@b.com" # Add new key
del person["city"] # Delete key
# Loop through a dict
for key, value in person.items():
print(f"{key}: {value}")
Dict Methods
| Method | Description |
|---|---|
.keys() | All keys |
.values() | All values |
.items() | All key-value pairs as tuples |
.get(key, default) | Safe access with fallback |
.update(other) | Merge another dict into this one |
.pop(key) | Remove key and return value |
Sets
Unordered collection of unique elements. Great for removing duplicates and set operations.
colors = {"red", "blue", "green", "red"}
print(colors) # {'red', 'blue', 'green'} — no duplicates!
# Remove duplicates from a list
nums = [1, 2, 2, 3, 3, 3]
unique = list(set(nums)) # [1, 2, 3]
# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5} — union
print(a & b) # {3} — intersection
print(a - b) # {1, 2} — difference
Defining Functions
def greet(name):
"""Greet a person by name."""
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Hello, Alice!
Parameters & Arguments
# Default parameters
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (uses default exponent=2)
print(power(3, 3)) # 27
# Keyword arguments
print(power(exponent=4, base=2)) # 16
# *args — variable number of arguments
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4)) # 10
# **kwargs — variable keyword arguments
def build_profile(**info):
return info
print(build_profile(name="Alice", age=25))
# {'name': 'Alice', 'age': 25}
Lambda Functions
Anonymous, one-line functions for simple operations:
square = lambda x: x ** 2
print(square(5)) # 25
# Useful with sorted(), map(), filter()
names = ["charlie", "alice", "bob"]
print(sorted(names, key=lambda n: len(n)))
# ['bob', 'alice', 'charlie']
Scope
Variables defined inside a function are local — they don't exist outside it. Variables defined outside are global and accessible everywhere (but avoid modifying them from inside functions — use return instead).
Write a Function
Create a function is_palindrome(text) that returns True if the text reads the same forwards and backwards.
Importing Modules
# Import entire module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
# Import specific things
from random import randint, choice
print(randint(1, 100)) # Random int between 1-100
# Import with alias
import datetime as dt
today = dt.date.today()
print(today) # 2026-04-08
Essential Standard Library Modules
math
sqrt, ceil, floor, pi, sin, cos
random
randint, choice, shuffle, sample
datetime
Date, time, timedelta operations
os / pathlib
File system operations, paths
json
Parse and write JSON data
urllib
HTTP requests, URL handling
Creating Your Own Module
# helpers.py — your custom module
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
# main.py — use your module
from helpers import celsius_to_fahrenheit
print(celsius_to_fahrenheit(37)) # 98.6
Installing Packages with pip
# Install a package
pip install requests
# Then use it
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
Creating a Class
class Dog:
# Constructor — runs when you create an instance
def __init__(self, name, breed):
self.name = name # Instance attribute
self.breed = breed
self.energy = 100
# Method
def bark(self):
return f"{self.name} says Woof!"
def play(self):
self.energy -= 20
return f"{self.name} plays! Energy: {self.energy}"
# Create instances (objects)
rex = Dog("Rex", "Labrador")
bella = Dog("Bella", "Poodle")
print(rex.bark()) # Rex says Woof!
print(bella.play()) # Bella plays! Energy: 80
Inheritance
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self):
return f"{self.name} makes a sound."
class Cat(Animal): # Cat inherits from Animal
def __init__(self, name, indoor=True):
super().__init__(name, "Cat") # Call parent's __init__
self.indoor = indoor
def speak(self): # Override parent method
return f"{self.name} says Meow!"
whiskers = Cat("Whiskers")
print(whiskers.speak()) # Whiskers says Meow!
print(whiskers.species) # Cat (inherited)
Dunder Methods (Magic Methods)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self): # String representation
return f"Point({self.x}, {self.y})"
def __add__(self, other): # Enable + operator
return Point(self.x + other.x, self.y + other.y)
def __eq__(self, other): # Enable == comparison
return self.x == other.x and self.y == other.y
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1 + p2) # Point(4, 6)
Reading Files
# Best practice: use 'with' — auto-closes the file
with open("data.txt", "r") as file:
content = file.read() # Read entire file
print(content)
# Read line by line (memory efficient for large files)
with open("data.txt") as file:
for line in file:
print(line.strip()) # strip() removes newline
Writing Files
# Write (creates or overwrites file)
with open("output.txt", "w") as file:
file.write("Hello, File!\n")
file.write("Second line.\n")
# Append (add to end without overwriting)
with open("output.txt", "a") as file:
file.write("Appended line.\n")
File Modes
| Mode | Description |
|---|---|
"r" | Read (default). Error if file doesn't exist. |
"w" | Write. Creates file or overwrites existing. |
"a" | Append. Creates file or adds to end. |
"x" | Create. Error if file already exists. |
"rb"/"wb" | Read/write binary (images, PDFs). |
Working with JSON
import json
# Write JSON
data = {"name": "Alice", "scores": [95, 87, 92]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON
with open("data.json") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
try / except
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred!") # Runs only if no exception
finally:
print("This ALWAYS runs.") # Cleanup
Common Exceptions
| Exception | When It Happens |
|---|---|
ValueError | Wrong type of value: int("abc") |
TypeError | Wrong operation for type: "a" + 1 |
KeyError | Dict key doesn't exist: d["nope"] |
IndexError | List index out of range: lst[999] |
FileNotFoundError | File doesn't exist: open("nope.txt") |
ZeroDivisionError | Dividing by zero: 5 / 0 |
AttributeError | Calling non-existent method |
Raising Exceptions
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age
try:
set_age(-5)
except ValueError as e:
print(e) # Age cannot be negative!
Best Practice: Catch specific exceptions, not bare except:. Be as precise as possible — it makes debugging much easier.
🎯 Project 1: Contact Book
📓 Requirements
Build a contact book that stores names, phone numbers, and emails. Support add, search, delete, and display all contacts. Store data in a JSON file so it persists between runs.
Contact Book
🎯 Project 2: Number Guessing Game
🎲 Requirements
Generate a random number 1-100. Let the player guess with "too high" / "too low" hints. Track number of guesses. Add difficulty levels (easy = 15 guesses, hard = 5).
Guessing Game
🎯 Project 3: Student Grade Tracker (OOP)
🎓 Requirements
Create a Student class with name, grades (list), and methods to add grades, get average, get letter grade, and display a summary. Then create a Classroom class that holds multiple students and can show rankings.
Student Tracker
🎉 Congratulations!
You've completed the Python Mastery course! You've learned variables, strings, operators, conditionals, loops, data structures, functions, modules, OOP, file handling, and error handling.
Keep building: Practice on LeetCode, HackerRank Python, or Exercism. Explore Django for web, Pandas for data, or Flask for APIs!