Python Basics
Variables & Data Types
# Variable assignment
x = 5
name = "Alice"
is_active = True
pi = 3.14159
# Multiple assignment
a, b, c = 1, 2, 3
# Dynamic typing
x = 5 # integer
x = "five" # now a string
x = 5
name = "Alice"
is_active = True
pi = 3.14159
# Multiple assignment
a, b, c = 1, 2, 3
# Dynamic typing
x = 5 # integer
x = "five" # now a string
Basic Operators
# Arithmetic
sum = 5 + 3
diff = 10 - 2
product = 4 * 5
quotient = 15 / 3 # float division
floor_div = 15 // 3 # integer division
remainder = 15 % 4
power = 2 ** 3 # 8 (2 to the power of 3)
# Comparison
x == y # equal
x != y # not equal
x > y
x <= y
# Logical
x and y
x or y
not x
sum = 5 + 3
diff = 10 - 2
product = 4 * 5
quotient = 15 / 3 # float division
floor_div = 15 // 3 # integer division
remainder = 15 % 4
power = 2 ** 3 # 8 (2 to the power of 3)
# Comparison
x == y # equal
x != y # not equal
x > y
x <= y
# Logical
x and y
x or y
not x
Control Flow
Conditionals
# If-elif-else
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
# Ternary operator
result = "Even" if x % 2 == 0 else "Odd"
# Truthy/Falsy values
if my_list: # False if empty
print("List has items")
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
# Ternary operator
result = "Even" if x % 2 == 0 else "Odd"
# Truthy/Falsy values
if my_list: # False if empty
print("List has items")
Loops
# For loop
for i in range(5):
print(i) # 0 to 4
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Loop control
for num in range(10):
if num == 3:
continue
if num == 7:
break
print(num)
for i in range(5):
print(i) # 0 to 4
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Loop control
for num in range(10):
if num == 3:
continue
if num == 7:
break
print(num)
Data Structures
Lists
# List creation
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
# List operations
numbers.append(6) # [1,2,3,4,5,6]
numbers.insert(0, 0) # [0,1,2,3,4,5,6]
numbers.remove(3) # removes first 3
popped = numbers.pop() # removes and returns 6
# Slicing
first_two = numbers[:2]
last_three = numbers[-3:]
reversed_list = numbers[::-1]
# List comprehension
squares = [x**2 for x in numbers if x % 2 == 0]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
# List operations
numbers.append(6) # [1,2,3,4,5,6]
numbers.insert(0, 0) # [0,1,2,3,4,5,6]
numbers.remove(3) # removes first 3
popped = numbers.pop() # removes and returns 6
# Slicing
first_two = numbers[:2]
last_three = numbers[-3:]
reversed_list = numbers[::-1]
# List comprehension
squares = [x**2 for x in numbers if x % 2 == 0]
Dictionaries
# Dictionary creation
person = {"name": "Alice", "age": 30}
# Accessing values
name = person["name"]
age = person.get("age", 0) # 0 is default
# Modifying
person["age"] = 31
person["city"] = "New York"
# Dictionary methods
keys = person.keys()
values = person.values()
items = person.items()
# Dictionary comprehension
squares = {x: x*x for x in range(5)}
# Merging dictionaries (Python 3.9+)
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = dict1 | dict2
person = {"name": "Alice", "age": 30}
# Accessing values
name = person["name"]
age = person.get("age", 0) # 0 is default
# Modifying
person["age"] = 31
person["city"] = "New York"
# Dictionary methods
keys = person.keys()
values = person.values()
items = person.items()
# Dictionary comprehension
squares = {x: x*x for x in range(5)}
# Merging dictionaries (Python 3.9+)
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = dict1 | dict2
Tuples & Sets
# Tuples (immutable)
point = (10, 20)
x, y = point # unpacking
# Single element tuple
single = (42,) # comma is required
# Sets (unique elements)
primes = {2, 3, 5, 7}
primes.add(11)
primes.discard(2)
# Set operations
odds = {1, 3, 5, 7, 9}
evens = {2, 4, 6, 8}
union = odds | evens
intersection = odds & primes
difference = odds - primes
point = (10, 20)
x, y = point # unpacking
# Single element tuple
single = (42,) # comma is required
# Sets (unique elements)
primes = {2, 3, 5, 7}
primes.add(11)
primes.discard(2)
# Set operations
odds = {1, 3, 5, 7, 9}
evens = {2, 4, 6, 8}
union = odds | evens
intersection = odds & primes
difference = odds - primes
Strings
# String creation
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = f"Hello {name}" # f-string (Python 3.6+)
# String methods
s = " Hello, World! "
s.strip() # "Hello, World!"
s.upper() # " HELLO, WORLD! "
s.replace("World", "Python")
words = s.split(",") # [' Hello', ' World! ']
# String formatting
name, age = "Alice", 30
msg = "{} is {} years old".format(name, age)
msg = f"{name} is {age} years old"
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = f"Hello {name}" # f-string (Python 3.6+)
# String methods
s = " Hello, World! "
s.strip() # "Hello, World!"
s.upper() # " HELLO, WORLD! "
s.replace("World", "Python")
words = s.split(",") # [' Hello', ' World! ']
# String formatting
name, age = "Alice", 30
msg = "{} is {} years old".format(name, age)
msg = f"{name} is {age} years old"
Functions
Function Basics
# Function definition
def greet(name):
return f"Hello, {name}!"
# Function with default arguments
def power(base, exponent=2):
return base ** exponent
# Function with variable arguments
def sum_all(*args):
return sum(args)
# Function with keyword arguments
def person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
def greet(name):
return f"Hello, {name}!"
# Function with default arguments
def power(base, exponent=2):
return base ** exponent
# Function with variable arguments
def sum_all(*args):
return sum(args)
# Function with keyword arguments
def person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Lambda & Advanced Functions
# Lambda functions
square = lambda x: x * x
result = square(5) # 25
# Using lambda with map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
# Using lambda with filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Using lambda with sorted
points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda x: x[1])
square = lambda x: x * x
result = square(5) # 25
# Using lambda with map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
# Using lambda with filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Using lambda with sorted
points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda x: x[1])
Advanced Topics
Classes & OOP
# Class definition
class Dog:
# Class attribute
species = "Canis familiaris"
# Initializer
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
# Creating instances
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)
# Inheritance
class Bulldog(Dog):
def run(self, speed):
return f"{self.name} runs at {speed} mph"
class Dog:
# Class attribute
species = "Canis familiaris"
# Initializer
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
# Creating instances
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)
# Inheritance
class Bulldog(Dog):
def run(self, speed):
return f"{self.name} runs at {speed} mph"
Error Handling
# Try-except block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
value = int("not_a_number")
except (ValueError, TypeError):
print("Value or type error occurred")
# Else and finally
try:
file = open("file.txt")
except FileNotFoundError:
print("File not found")
else:
print(file.read())
file.close()
finally:
print("Execution complete")
# Raising exceptions
if x < 0:
raise ValueError("x should be non-negative")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
value = int("not_a_number")
except (ValueError, TypeError):
print("Value or type error occurred")
# Else and finally
try:
file = open("file.txt")
except FileNotFoundError:
print("File not found")
else:
print(file.read())
file.close()
finally:
print("Execution complete")
# Raising exceptions
if x < 0:
raise ValueError("x should be non-negative")