Python Basics Cheat Sheet
1. VARIABLES & DATA TYPES
-x=5 # int
- y = 3.14 # float
- name = "Alice" # string
- flag = True # bool
2. STRINGS
- name.upper(), name.lower()
- name[0:3], len(name), name.replace("a", "e")
3. LISTS
- nums = [1, 2, 3]
- nums.append(4), nums.remove(2), nums[1]
4. TUPLES & SETS
- tup = (1, 2), s = {1, 2, 3}
- set operations: union, intersection
5. DICTIONARIES
- d = {"a": 1, "b": 2}
- d["a"], d.keys(), d.values()
6. CONDITIONALS
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
7. LOOPS
for i in range(5): print(i)
while x < 5: x += 1
8. FUNCTIONS
def greet(name):
return "Hello " + name
9. CLASSES
class Person:
def __init__(self, name):
self.name = name
def say(self):
print(self.name)
10. FILE HANDLING
with open("file.txt", "r") as f:
data = f.read()
11. EXCEPTION HANDLING
try:
x=1/0
except ZeroDivisionError:
print("Error")
12. LAMBDA & LIST COMPREHENSION
add = lambda x, y: x + y
squares = [x**2 for x in range(5)]