Data Types & Variables
Basic Types
# Variables are dynamically typed
age = 25 # int
price = 19.99 # float
name = "Alice" # str
is_active = True # bool
# f-Strings for formatting
greeting = f"Hello {name}, you are {age} years old."Data Structures
Lists, Tuples, Sets, Dictionaries
# List: Ordered, Mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
# Tuple: Ordered, Immutable
coordinates = (10.0, 20.0)
# Set: Unordered, Unique elements
ids = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
# Dictionary: Key-Value pairs
user = {
"name": "Bob",
"age": 30
}
print(user["name"]) # BobControl Flow
If/Else & Loops
# Conditionals
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
# For Loop (Iterating over a list)
for fruit in fruits:
print(fruit)
# For Loop (Range)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# While Loop
while count > 0:
print(count)
count -= 1Functions
Definitions & Arguments
def greet(name, msg="Hello"):
"""Docstring: Greets a person."""
return f"{msg}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Welcome")) # Welcome, Bob!
# *args for variable positional arguments
def sum_all(*args):
return sum(args)Comprehensions
List & Dict Comprehensions
Concise way to create lists or dictionaries based on existing iterables.
# List Comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With Condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Dictionary Comprehension
sq_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Classes & OOP
Basic Class Structure
class Dog:
# Class attribute
species = "Canis familiaris"
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def bark(self):
return f"{self.name} says woof!"
# Instantiation
my_dog = Dog("Rex", 5)
print(my_dog.bark())