๐ Python 3.x ยท Beginner โ Advanced
Python Complete Cheatsheet
Everything you need to write Python โ from variables to OOP to file handling. Each section has runnable examples, tips, and mini quizzes to test your knowledge.
01
Basics & Syntax
โผ
Variables & Assignment
PythonBasic variable assignment
# Variables โ no type declaration needed name = "Ahmed" # string age = 17 # integer gpa = 3.85 # float is_student = True # boolean # Multiple assignment x, y, z = 1, 2, 3 # Augmented assignment count = 0 count += 1 # same as count = count + 1 count -= 1 count *= 2 # Type checking print(type(name)) # <class 'str'> print(type(age)) # <class 'int'>
Print & Input
PythonOutput and user input
# Print โ multiple ways print("Hello, World!") print("Name:", name) print(f"Hello, {name}! Age: {age}") # f-string (best) print("Score:", gpa, sep="") # custom separator print("A", end="") # no newline # Input from user name = input("Enter your name: ") age = int(input("Enter age: ")) # convert to int! # Type conversion int("42") # โ 42 float("3.14") # โ 3.14 str(100) # โ "100" bool(0) # โ False (0, "", [], None are Falsy)
Operators
| Operator | Symbol | Example | Result |
|---|---|---|---|
| Addition | + | 5 + 3 | 8 |
| Subtraction | - | 10 - 4 | 6 |
| Multiplication | * | 3 * 4 | 12 |
| Division | / | 10 / 3 | 3.333โฆ |
| Floor Division | // | 10 // 3 | 3 |
| Modulus (remainder) | % | 10 % 3 | 1 |
| Exponentiation | ** | 2 ** 8 | 256 |
| Comparison | Symbol | Logical | Symbol |
|---|---|---|---|
| Equal | == | And | and |
| Not equal | != | Or | or |
| Greater than | > | Not | not |
| Less than or equal | <= | Is same object | is |
๐ก
Remember: = is assignment, == is comparison! Common beginner bug: using = inside an if condition instead of ==.
02
Data Types
โผ
int
Whole numbers:
No size limit in Python!
x = 42, x = -10, x = 0No size limit in Python!
float
Decimals:
Use
x = 3.14, x = 2.0, x = -0.5Use
round(x, 2) for roundingstr
Text:
Triple quotes for multiline:
"hello" or 'world'Triple quotes for multiline:
"""text"""bool
Only
Falsy:
True or FalseFalsy:
0, "", [], {}, Nonelist
Ordered, mutable:
Can hold mixed types
[1, 2, 3]Can hold mixed types
tuple
Ordered, immutable:
Faster than list, use for fixed data
(1, 2, 3)Faster than list, use for fixed data
dict
Key-value pairs:
Keys must be unique & immutable
{"key": "val"}Keys must be unique & immutable
set
Unique unordered items:
No duplicates, no indexing
{1, 2, 3}No duplicates, no indexing
03
Control Flow
โผ
PythonIf / elif / else
if age >= 18: print("Adult") elif age >= 13: print("Teenager") else: print("Child") # One-liner (ternary) label = "Adult" if age >= 18 else "Minor" # Nested conditions if score >= 90 and attendance >= 80: grade = "A" elif score >= 70 or bonus_marks: grade = "B"
Pythonfor and while loops
# for loop โ iterate over range for i in range(5): # 0,1,2,3,4 print(i) for i in range(1, 11, 2): # 1,3,5,7,9 (start,stop,step) print(i) # for loop โ iterate over list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # enumerate โ get index AND value for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # while loop count = 0 while count < 5: print(count) count += 1 # break and continue for n in range(10): if n == 5: break # exit loop if n % 2 == 0: continue # skip to next print(n) # prints 1, 3
04
Functions
โผ
PythonFunction definitions
# Basic function def greet(name): return f"Hello, {name}!" print(greet("Ahmed")) # Hello, Ahmed! # Default parameters def power(base, exp=2): return base ** exp power(3) # 9 (uses default exp=2) power(3, 3) # 27 # *args โ variable number of arguments def total(*numbers): return sum(numbers) total(1, 2, 3, 4) # 10 # **kwargs โ keyword arguments def profile(**info): for key, val in info.items(): print(f"{key}: {val}") profile(name="Ahmed", age=17, city="Lahore") # Lambda (anonymous function) square = lambda x: x ** 2 print(square(5)) # 25 add = lambda a, b: a + b print(add(3, 4)) # 7 # Multiple return values def min_max(lst): return min(lst), max(lst) lo, hi = min_max([3, 1, 7, 2]) # lo=1, hi=7
โญ
List Comprehension โ Pythonic one-line list creation:
squares = [x**2 for x in range(10)]evens = [x for x in range(20) if x % 2 == 0]
05
Lists & Tuples
โผ
PythonList operations
nums = [3, 1, 4, 1, 5, 9] # Indexing & slicing nums[0] # 3 (first) nums[-1] # 9 (last) nums[1:4] # [1, 4, 1] (slice) nums[::-1] # [9,5,1,4,1,3] (reverse) # Methods nums.append(2) # add to end nums.insert(0, 10) # insert at index nums.remove(1) # remove first occurrence nums.pop() # remove and return last nums.pop(2) # remove at index 2 nums.sort() # sort in-place nums.sort(reverse=True) # sort descending nums.reverse() # reverse in-place nums.count(1) # count occurrences nums.index(5) # find index of value len(nums) # length # Useful built-ins sorted(nums) # return sorted copy sum(nums) # sum all elements min(nums), max(nums) # min and max list(set(nums)) # remove duplicates # List comprehension squares = [x**2 for x in nums] big = [x for x in nums if x > 3]
06
Dictionaries & Sets
โผ
PythonDictionary operations
student = {"name": "Ahmed", "age": 17, "gpa": 3.8}
# Access
student["name"] # "Ahmed"
student.get("grade", "N/A") # safe access with default
# Modify
student["age"] = 18 # update value
student["city"] = "Lahore" # add new key
del student["gpa"] # delete key
# Iterate
for key in student: # keys
print(key)
for val in student.values(): # values
print(val)
for k, v in student.items(): # both
print(f"{k}: {v}")
# Methods
student.keys() # dict_keys([...])
student.values() # dict_values([...])
student.pop("age") # remove & return
student.update({"score": 95}) # merge/update
in student # check key exists
# Sets โ unique unordered elements
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # union {1,2,3,4,5,6}
a & b # intersection {3,4}
a - b # difference {1,2}
a.add(10) # add element
a.remove(1) # remove element
07
String Methods
โผ
PythonEssential string methods
s = " Hello, World! " # Case s.upper() # " HELLO, WORLD! " s.lower() # " hello, world! " s.title() # " Hello, World! " # Strip whitespace s.strip() # "Hello, World!" s.lstrip() # "Hello, World! " (left only) s.rstrip() # " Hello, World!" (right only) # Search s.find("World") # 9 (index) or -1 if not found s.count("l") # 3 "Hello" in s # True s.startswith(" H") # True s.endswith(" ") # True # Modify s.replace("World", "Python") # replace ", ".join(["a", "b", "c"]) # "a, b, c" s.split(",") # [" Hello", " World! "] # Format f"Name: {name}, Age: {age}" # f-string (Python 3.6+) f"Pi = {3.14159:.2f}" # "Pi = 3.14" f"{1000000:,}" # "1,000,000" f"{0.75:.0%}" # "75%" # Slicing strings word = "Python" word[0] # "P" word[-1] # "n" word[2:5] # "tho" word[::-1] # "nohtyP" (reverse)
08
OOP โ Classes & Objects
โผ
PythonClass definition and inheritance
class Animal: # Class variable (shared by all instances) species_count = 0 def __init__(self, name, sound): # Instance variables self.name = name self.sound = sound Animal.species_count += 1 def speak(self): return f"{self.name} says {self.sound}!" def __str__(self): # for print() return f"Animal: {self.name}" def __repr__(self): # for debugging return f"Animal('{self.name}')" # Create objects dog = Animal("Dog", "Woof") cat = Animal("Cat", "Meow") print(dog.speak()) # Dog says Woof! # Inheritance class Dog(Animal): def __init__(self, name, breed): super().__init__(name, "Woof") # call parent __init__ self.breed = breed def fetch(self): # new method return f"{self.name} fetches the ball!" def speak(self): # override parent method return f"{self.name} barks loudly!" rex = Dog("Rex", "German Shepherd") print(rex.speak()) # Rex barks loudly! print(rex.fetch()) # Rex fetches the ball! isinstance(rex, Animal) # True
09
File I/O
โผ
PythonReading and writing files
# Writing a file with open("data.txt", "w") as f: f.write("Hello, File!\n") f.write("Second line\n") # Reading a file โ full content with open("data.txt", "r") as f: content = f.read() print(content) # Reading line by line with open("data.txt", "r") as f: for line in f: print(line.strip()) # Read all lines as list with open("data.txt") as f: lines = f.readlines() # ['Hello, File!\n', ...] # Append to file with open("data.txt", "a") as f: f.write("Appended line\n") # File modes: "r" read, "w" write, "a" append, "rb" binary
10
Error Handling
โผ
Pythontry / except / finally
try: num = int(input("Enter a number: ")) result = 100 / num print(f"Result: {result}") except ValueError: print("Error: Please enter a valid number") except ZeroDivisionError: print("Error: Cannot divide by zero") except Exception as e: print(f"Unexpected error: {e}") else: print("No error occurred!") # runs if no exception finally: print("This always runs") # cleanup code # Raise your own exceptions def validate_age(age): if age < 0: raise ValueError("Age cannot be negative") return age
| Exception | Cause |
|---|---|
| ValueError | Wrong value type (e.g., int("abc")) |
| TypeError | Wrong type operation ("2" + 2) |
| ZeroDivisionError | Dividing by zero |
| IndexError | List index out of range |
| KeyError | Dictionary key not found |
| FileNotFoundError | File doesn't exist |
| NameError | Variable not defined |
| AttributeError | Object has no attribute |
11
Modules & Libraries
โผ
PythonBuilt-in modules
import math math.sqrt(16) # 4.0 math.pi # 3.14159โฆ math.ceil(3.2) # 4 math.floor(3.8) # 3 import random random.random() # 0.0 to 1.0 random.randint(1, 6) # dice roll 1-6 random.choice(["a","b","c"]) # random pick random.shuffle(my_list) # shuffle in-place import datetime now = datetime.datetime.now() print(now.strftime("%Y-%m-%d %H:%M")) from collections import Counter, defaultdict word_count = Counter(["a","b","a","c","a"]) # Counter({'a': 3, 'b': 1, 'c': 1}) # os module import os os.getcwd() # current directory os.listdir(".") # list files os.path.exists("file.txt") # check if exists
pip install
pip install numpypip install pandaspip install matplotlibpip install requestsPopular Libraries
NumPy โ arrays & math
Pandas โ data analysis
Matplotlib โ plotting
Requests โ HTTP/API
Pandas โ data analysis
Matplotlib โ plotting
Requests โ HTTP/API
Virtual Env
python -m venv envsource env/bin/activatepip freeze > req.txtpip install -r req.txt
12
Test Your Knowledge โ Mini Quizzes
โผ
โ Quiz 1
What does
list(range(2, 10, 3)) produce?range(start=2, stop=10, step=3) โ starts at 2, adds 3 each time: 2, 5, 8. Stops before 10.
โ Quiz 2
What is the output of:
print(10 // 3, 10 % 3)?// is floor division (rounds down): 10//3 = 3. % is modulus (remainder): 10%3 = 1 (since 3ร3=9, remainder is 1).
โ Quiz 3
Which of these correctly creates a set in Python?
Sets use curly braces {1, 2, 3}. Note: {} creates an empty dict โ use set() for empty set. (1,2,3) is a tuple, [1,2,3] is a list.
โ Quiz 4
What does
lambda x: x**2 do?Lambda creates a small anonymous (nameless) function. lambda x: x**2 takes one argument x and returns xยฒ. Use like: f = lambda x: x**2; f(5) returns 25.