Python Notes Cheat Sheet
1. Basic Syntax
# This is a comment
print("Hello, world!")
2. Variables and Data Types
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
is_valid = True # Boolean
3. Data Structures - Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
print(fruits[1]) # banana
Tuples
coords = (4, 5)
Dictionaries
person = {"name": "Alice", "age": 25}
print(person["name"])
Sets
unique = {1, 2, 3}
4. Control Flow - If-Else
x = 5
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Loops
# For loop
Python Notes Cheat Sheet
for i in range(5):
print(i)
# While loop
i = 0
while i < 5:
print(i)
i += 1
5. Functions
def greet(name):
return f"Hello, {name}"
print(greet("John"))
6. Classes and Objects
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
d = Dog("Buddy")
d.bark()
7. File Handling
# Write to file
with open("file.txt", "w") as f:
f.write("Hello!")
# Read from file
with open("file.txt", "r") as f:
print(f.read())
8. Modules and Libraries
import math
print(math.sqrt(16)) # 4.0
Python Notes Cheat Sheet
9. Exception Handling
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Done.")