Variables & Data Types
Python variables are containers for storing data values. Python has several built-in data types.
# Variable Assignment
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
# Type Checking
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True
# Type Conversion
str_num = "123"
int_num = int(str_num) # Convert to integer
float_num = float(str_num) # Convert to float
Key Points:
- Python is dynamically typed
- Variable names must start with letter or underscore
- Use
type()
to check data type - Main types: int, float, str, bool, list, tuple, dict, set
Lists
Lists are ordered, mutable collections that can store multiple items.
# Creating Lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# List Methods
fruits.append("grape") # Add to end
fruits.insert(1, "mango") # Insert at index
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove last item
# List Operations
print(len(fruits)) # Length
print(fruits[0]) # First item
print(fruits[-1]) # Last item
print(fruits[1:3]) # Slicing
# List Comprehension Preview
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Key Points:
- Lists are mutable (can be changed)
- Indexed from 0, negative indexing supported
- Can contain different data types
- Common methods: append(), insert(), remove(), pop()
Tuples
Tuples are ordered, immutable collections. Once created, they cannot be changed.
# Creating Tuples
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (42,) # Note the comma for single item
# Tuple Operations
print(coordinates[0]) # Accessing elements
print(len(colors)) # Length
print("red" in colors) # Membership test
# Tuple Unpacking
x, y = coordinates # x=10, y=20
first, *rest = colors # first="red", rest=["green", "blue"]
# Tuple Methods (only 2!)
numbers = (1, 2, 2, 3, 2)
print(numbers.count(2)) # Count occurrences: 3
print(numbers.index(3)) # Find index of value: 3
Key Points:
- Tuples are immutable (cannot be changed)
- Faster than lists for fixed data
- Can be used as dictionary keys
- Perfect for coordinates, RGB values, database records
Sets
Sets are unordered collections of unique elements. No duplicates allowed.
# Creating Sets
fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 3, 2, 1]) # {1, 2, 3} - duplicates removed
# Set Operations
fruits.add("grape") # Add element
fruits.discard("banana") # Remove element (no error if not found)
fruits.remove("apple") # Remove element (error if not found)
# Set Math Operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2 # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2 # {3, 4}
difference = set1 - set2 # {1, 2}
symmetric_diff = set1 ^ set2 # {1, 2, 5, 6}
# Set Methods
print(len(fruits)) # Size
print("apple" in fruits) # Membership test
Key Points:
- Sets contain unique elements only
- Unordered - no indexing
- Mutable but elements must be immutable
- Great for removing duplicates and set operations
Dictionaries
Dictionaries store key-value pairs. Keys must be unique and immutable.
# Creating Dictionaries
student = {"name": "Alice", "age": 20, "grade": "A"}
empty_dict = {}
dict_from_pairs = dict([("a", 1), ("b", 2)])
# Dictionary Operations
print(student["name"]) # Access value
student["city"] = "NYC" # Add new key-value
student["age"] = 21 # Update existing value
del student["grade"] # Delete key-value pair
# Dictionary Methods
keys = student.keys() # Get all keys
values = student.values() # Get all values
items = student.items() # Get key-value pairs
# Safe Access
age = student.get("age", 0) # Returns 0 if key not found
popped = student.pop("city", None) # Remove and return value
# Dictionary Comprehension Preview
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
Key Points:
- Keys must be unique and immutable
- Values can be any data type
- Insertion order preserved (Python 3.7+)
- Use get() method for safe access
Loops & Conditionals
Control flow statements to make decisions and repeat actions.
# If-Elif-Else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
# For Loops
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
for i in range(5): # 0 to 4
print(i)
for i, fruit in enumerate(fruits): # Get index and value
print(f"{i}: {fruit}")
# While Loops
count = 0
while count < 5:
print(count)
count += 1
# Loop Control
for i in range(10):
if i == 3:
continue # Skip this iteration
if i == 7:
break # Exit loop
print(i)
Key Points:
- Indentation defines code blocks
- Use elif for multiple conditions
- for loops iterate over sequences
- while loops continue until condition is False
- break exits loop, continue skips iteration
String Manipulation
Strings are sequences of characters with many built-in methods.
# String Creation
name = "Alice"
message = 'Hello World'
multiline = """This is
a multiline
string"""
# String Methods
text = " Hello Python World "
print(text.strip()) # Remove whitespace
print(text.lower()) # Convert to lowercase
print(text.upper()) # Convert to uppercase
print(text.replace("Python", "Java")) # Replace substring
# String Checking
print(text.startswith("Hello")) # False (whitespace)
print(text.strip().startswith("Hello")) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True
# String Formatting
name = "Alice"
age = 25
# f-strings (Python 3.6+)
message = f"My name is {name} and I'm {age} years old"
# format() method
message = "My name is {} and I'm {} years old".format(name, age)
# % formatting (older)
message = "My name is %s and I'm %d years old" % (name, age)
# String Slicing
text = "Python"
print(text[0]) # 'P'
print(text[-1]) # 'n'
print(text[1:4]) # 'yth'
print(text[::-1]) # 'nohtyP' (reverse)
Key Points:
- Strings are immutable
- Many useful methods: strip(), split(), join(), replace()
- f-strings are the modern way to format strings
- Slicing works like lists
Functions & Recursion
Functions are reusable blocks of code. Recursion is when a function calls itself.
# Basic Function
def greet(name):
return f"Hello, {name}!"
# Function with Default Parameters
def greet_with_title(name, title="Mr/Ms"):
return f"Hello, {title} {name}!"
# Function with Multiple Return Values
def get_name_age():
return "Alice", 25
name, age = get_name_age() # Tuple unpacking
# Variable Arguments
def sum_all(*args): # *args for multiple positional arguments
return sum(args)
def print_info(**kwargs): # **kwargs for keyword arguments
for key, value in kwargs.items():
print(f"{key}: {value}")
# Recursion Example - Factorial
def factorial(n):
if n <= 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call
# Recursion Example - Fibonacci
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Local vs Global Variables
global_var = "I'm global"
def my_function():
local_var = "I'm local"
global global_var
global_var = "Modified global"
return local_var
Key Points:
- Functions promote code reusability
- Use def keyword to define functions
- Recursion needs a base case to stop
- *args and **kwargs for flexible parameters
- Local variables exist only within function scope
List Comprehension & Lambda
Advanced techniques for creating lists and small anonymous functions.
# List Comprehension - Basic
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers] # [1, 4, 9, 16, 25]
# List Comprehension with Condition
evens = [x for x in numbers if x % 2 == 0] # [2, 4]
# List Comprehension with if-else
result = [x**2 if x % 2 == 0 else x**3 for x in numbers]
# Nested List Comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row] # [1,2,3,4,5,6,7,8,9]
# Dictionary Comprehension
squares_dict = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
# Set Comprehension
unique_squares = {x**2 for x in [1, -1, 2, -2]} # {1, 4}
# Lambda Functions
add = lambda x, y: x + y
print(add(5, 3)) # 8
# Lambda with Built-in Functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# Sorting with Lambda
students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
sorted_by_grade = sorted(students, key=lambda x: x[1]) # Sort by grade
# Lambda in List Comprehension
operations = [(lambda x: x**2), (lambda x: x**3), (lambda x: x**0.5)]
results = [op(4) for op in operations] # [16, 64, 2.0]
Key Points:
- List comprehensions are more Pythonic than loops
- Syntax: [expression for item in iterable if condition]
- Lambda functions are small, anonymous functions
- Great with map(), filter(), and sorted()
- Use comprehensions for simple operations only