1. Basics & Syntax
Python is designed to be highly readable. It uses indentation (spaces) rather than curly braces to define blocks of code.
print("Hello, World!")
name = "Alice"
age = 25
2. Core Data Types
Python has several built-in data types that handle text, numbers, and boolean logic.
text = "Hello"
multi = '''Line 1
Line 2'''
integer_num = 42
floating_num = 3.14159
is_active = True
is_empty = False
empty_val = None
3. Operators & Math
Python supports standard mathematical operations and logic comparisons.
add = 5 + 3
sub = 5 - 3
mul = 5 * 3
div = 10 / 3
floor = 10 // 3
mod = 10 % 3
exp = 2 ** 3
and, or, not
4. Control Flow
Control the execution path of your program using conditional logic and loops.
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
for i in range(5):
print(i)
count = 5
while count > 0:
count -= 1
5. Collections
Lists, Tuples, Sets, and Dictionaries store multiple items.
fruits = ["apple", "banana"]
fruits.append("orange")
coords = (10.0, 20.0)
unique_nums = {1, 2, 2, 3}
user = {"name": "John", "age": 30}
print(user.get("name"))
6. Functions & Lambdas
Functions allow for code reuse. Lambdas are small anonymous functions.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
multiply = lambda x, y: x * y
print(multiply(5, 4))
7. Object-Oriented Programming
Classes map software objects to real-world entities.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
dog = Dog("Rex")
print(dog.speak())
8. Error Handling
Handle exceptions gracefully so your program doesn't crash unexpectedly.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("This runs no matter what.")
9. Comprehensions
A concise way to create lists, dictionaries, or sets based on existing iterables.
squares = [x**2 for x in range(5)]
square_dict = {x: x**2 for x in range(5)}