1. Variables & Data Types
# Basic Data Types
name = "Alice" # String
age = 25 # Integer
height = 5.8 # Float
is_student = True # Boolean
items = [1, 2, 3] # List
coordinates = (10, 20) # Tuple
person = {"name": "Bob"} # Dictionary
unique_nums = {1, 2, 3} # Set
- Strings: Immutable text data
- Lists: Mutable, ordered collections
- Tuples: Immutable, ordered collections
- Dictionaries: Key-value pairs
- Sets: Unique elements only
2. String Operations
text = "Hello World"
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.split()) # ['Hello', 'World']
print(len(text)) # 11
print(text[0]) # H
print(text[1:5]) # ello
# f-strings (Modern way)
name = "Alice"
age = 25
print(f"Hi {name}, you're {age}")
Hi Alice, you're 25
3. Lists & Methods
fruits = ["apple", "banana"]
fruits.append("cherry") # Add to end
fruits.insert(1, "grape") # Insert at index
fruits.remove("banana") # Remove item
fruits.sort() # Sort in place
# List comprehension
squares = [x**2 for x in range(1, 6)]
evens = [x for x in range(10) if x % 2 == 0]
[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]
4. Control Flow
# If-elif-else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
# Loops
for i in range(5): # 0, 1, 2, 3, 4
print(i)
fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)
5. Functions
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Lambda functions
square = lambda x: x**2
print(square(5)) # 25
# Map and Filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
6. Exception Handling
try:
num = int(input("Enter number: "))
result = 10 / num
print(f"Result: {result}")
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error: {e}")
finally:
print("Always executes")