Python Cheat Sheet
Complete Reference - All 5 Units Consolidated
UNIT I: Introduction to Python
Python Basics
Python is a high-level, interpreted, dynamically-typed language created by Guido van Rossum (1991).
print("Hello, World!")
Variables
name = "John" # No type declaration
x, y, z = 10, 20, 30 # Multiple
x, y = y, x # Swap values
Data Types
| Category | Types |
|---|---|
| Text | str |
| Numeric | int, float, complex |
| Sequence | list, tuple, range |
| Mapping | dict |
| Set | set, frozenset |
| Boolean | bool (True/False) |
| None | NoneType |
Type Conversion
int("100"), str(25), float(10), list("abc")
Arithmetic Operators
| Addition | x + y |
| Subtraction | x - y |
| Multiplication | x * y |
| Division | x / y |
| Floor Division | x // y |
| Modulus | x % y |
| Exponentiation | x ** y |
Comparison Operators
| Equal | x == y |
| Not equal | x != y |
| Greater than | x > y |
| Less than | x < y |
| Greater or equal | x >= y |
| Less or equal | x <= y |
Logical & Identity
Logical
| AND | x and y |
| OR | x or y |
| NOT | not x |
Identity & Membership
| Same object | x is y |
| Not same | x is not y |
| In sequence | x in y |
| Not in | x not in y |
Assignment Operators
| Assign | x = 5 |
| Add & assign | x += 3 |
| Subtract & assign | x -= 3 |
| Multiply & assign | x *= 3 |
| Divide & assign | x /= 3 |
| Floor div & assign | x //= 3 |
| Modulus & assign | x %= 3 |
| Power & assign | x **= 3 |
Bitwise Operators
| Operator | Description |
|---|---|
| & | AND |
| | | OR |
| ^ | XOR |
| ~ | NOT |
| << | Left shift |
| >> | Right shift |
Operator Precedence
Highest to Lowest:
| Precedence | Operator |
|---|---|
| 1 (Highest) | () Parentheses |
| 2 | ** Exponent |
| 3 | ~, +x, -x (Unary) |
| 4 | *, /, //, % |
| 5 | +, - (Binary) |
| 6 | <<, >> (Shift) |
| 7 | & (Bitwise AND) |
| 8 | ^ (Bitwise XOR) |
| 9 | | (Bitwise OR) |
| 10 | ==, !=, <, >, <=, >= |
| 11 | not |
| 12 | and |
| 13 (Lowest) | or |
UNIT II: Program Flow Control
Conditional Statements
if condition:
# code
elif another:
# code
else:
# code
Ternary Operator
result = "Yes" if condition else "No"
For Loops
for item in iterable:
print(item)
# With index
for i, item in enumerate(lst):
print(i, item)
Range Function
| Syntax | Output |
|---|---|
| range(5) | 0, 1, 2, 3, 4 |
| range(2, 7) | 2, 3, 4, 5, 6 |
| range(0, 10, 2) | 0, 2, 4, 6, 8 |
| range(10, 0, -1) | 10, 9, ...1 |
While Loops
count = 5
while count > 0:
print(count)
count -= 1
⚠️ Always update condition inside loop to avoid infinite loops!
Loop Control
break | Exit loop immediately |
continue | Skip to next iteration |
pass | Do nothing (placeholder) |
else | Runs if no break |
for i in range(10):
if i == 5: break
else:
print("No break")
Python Blocks
Python uses indentation (4 spaces) to define code blocks. No curly braces!
if True:
print("Indented")
if True:
print("Nested")
Iteration Patterns
| Pattern | Example |
|---|---|
| Iterate list | for x in list |
| With index | for i, x in enumerate() |
| Two lists | for a, b in zip(x, y) |
| Dict keys | for k in dict |
| Dict items | for k, v in dict.items() |
| Reverse | for x in reversed(list) |
Nested Loops
for i in range(3):
for j in range(3):
print(i, j)
| Use Case | Pattern |
|---|---|
| 2D matrix | for row for col |
| Combinations | for a for b |
| Pattern print | Nested range |
UNIT III: Complex Data Types & Functions
Strings
text = "Hello, World!"
text[0] # 'H' (first char)
text[-1] # '!' (last char)
text[0:5] # 'Hello' (slice)
text[::-1] # Reverse string
f-Strings
name = "Alice"
print(f"Hello, {name}!")
String Methods
| upper(), lower() | Change case |
| strip() | Remove whitespace |
| split(sep) | Split to list |
| join(list) | Join list to str |
| find(sub) | Find index (-1 if not) |
| replace(old, new) | Replace text |
| startswith() | Check prefix |
| isdigit(), isalpha() | Validation |
Lists
my_list = [1, 2, "a", "b"]
my_list[0] # First item
my_list[-1] # Last item
my_list[1:3] # Slice [2, 'a']
my_list[0] = 10 # Mutable!
List Comprehension
[x**2 for x in range(5)]
[x for x in lst if x > 0]
List Methods
| append(x) | Add to end |
| insert(i, x) | Add at index |
| extend(list) | Add multiple |
| remove(x) | Remove first x |
| pop(i) | Remove & return |
| sort() | Sort in-place |
| reverse() | Reverse in-place |
| index(x) | Find index |
| count(x) | Count occurrences |
Tuples
Immutable sequences - faster than lists, can be dict keys.
coords = (10, 20, 30)
x, y, z = coords # Unpacking
single = (5,) # Single element tuple
Tuple vs List
| Tuple | Immutable, faster |
| List | Mutable, flexible |
Dictionaries
person = {"name": "Alice", "age": 25}
person["name"] # "Alice"
person["city"] = "NYC" # Add key
person.get("job", "N/A") # Safe access
| keys() | All keys |
| values() | All values |
| items() | Key-value pairs |
| update(d) | Merge dicts |
Functions
def greet(name, msg="Hello"):
"""Docstring"""
return f"{msg}, {name}!"
greet("Alice") # "Hello, Alice!"
Lambda & *args/**kwargs
Lambda (Anonymous)
square = lambda x: x ** 2
square(5) # 25
*args & **kwargs
def func(*args, **kwargs):
print(args) # Tuple
print(kwargs) # Dict
Built-in Functions
| len(x) | Length |
| type(x) | Get type |
| range(n) | Number sequence |
| max(), min() | Max/Min value |
| sum() | Sum of iterable |
| sorted() | Sorted copy |
| enumerate() | Index + value |
| zip(a, b) | Pair items |
| input() | User input |
Slicing Syntax
| Syntax | Result |
|---|---|
| seq[start:end] | Items start to end-1 |
| seq[:end] | From beginning |
| seq[start:] | To end |
| seq[::step] | Every step items |
| seq[::-1] | Reverse |
| seq[-3:] | Last 3 items |
Sets
s = {1, 2, 3} # Unique items
| Method | Description |
|---|---|
| add(x) | Add element |
| remove(x) | Remove (error if missing) |
| discard(x) | Remove (no error) |
| union(s2) | All from both |
| intersection(s2) | Common elements |
| difference(s2) | In s1 not s2 |
Comprehensions
| Type | Syntax |
|---|---|
| List | [x for x in iter] |
| Dict | {k:v for k,v in iter} |
| Set | {x for x in iter} |
| Generator | (x for x in iter) |
squares = {x: x**2 for x in range(5)}
UNIT IV: File Operations
File Modes
| Mode | Description |
|---|---|
| 'r' | Read (default) |
| 'w' | Write (overwrite) |
| 'a' | Append |
| 'x' | Exclusive create |
| 'r+' | Read + Write |
| 'b' | Binary ('rb', 'wb') |
Reading Files
with open("file.txt", "r") as f:
content = f.read() # All
line = f.readline() # One line
lines = f.readlines() # List
| read() | Entire file |
| readline() | Single line |
| readlines() | List of lines |
| for line in f | Iterate (best) |
Writing Files
with open("file.txt", "w") as f:
f.write("Hello\n")
f.writelines(["a\n", "b\n"])
Note: write() doesn't add newlines automatically!
File Pointer
f.tell() # Current position
f.seek(0) # Go to start
f.seek(10) # Go to position 10
Context Manager (with) automatically closes files!
UNIT V: Python Packages & GUI
NumPy
import numpy as np
arr = np.array([1, 2, 3])
np.zeros((3, 4)) # 3x4 zeros
np.ones((2, 3)) # 2x3 ones
np.arange(0, 10, 2) # [0,2,4,6,8]
| arr.shape | Dimensions |
| arr.reshape() | Reshape array |
| np.sum(), mean() | Aggregations |
| arr.T | Transpose |
Pandas
import pandas as pd
df = pd.DataFrame({
'Name': ['A', 'B'],
'Age': [25, 30]
})
df = pd.read_csv('file.csv')
| df['col'] | Select column |
| df.iloc[0] | Row by index |
| df[df['Age']>25] | Filter rows |
| df.head(n) | First n rows |
| df.describe() | Statistics |
Matplotlib
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.title('Title')
plt.xlabel('X'); plt.ylabel('Y')
plt.legend(); plt.show()
| plt.plot() | Line plot |
| plt.bar() | Bar chart |
| plt.scatter() | Scatter plot |
| plt.hist() | Histogram |
| plt.pie() | Pie chart |
Tkinter Widgets
| tk.Tk() | Main window |
| tk.Label() | Display text |
| tk.Button() | Clickable button |
| tk.Entry() | Text input |
| tk.Text() | Multi-line input |
| tk.Frame() | Container |
| tk.Checkbutton() | Checkbox |
| tk.Listbox() | Scrollable list |
Tkinter Layout
| Method | Use |
|---|---|
| pack() | Simple stacking |
| grid(row, col) | Table layout |
| place(x, y) | Exact position |
import tkinter as tk
root = tk.Tk()
root.title("App")
tk.Label(root, text="Hi").pack()
root.mainloop()
Error Handling
try:
result = 10 / x
except ZeroDivisionError:
print("Cannot divide by 0")
except Exception as e:
print(e)
finally:
print("Cleanup")
Common Errors
| SyntaxError | Invalid syntax |
| NameError | Undefined variable |
| TypeError | Wrong type operation |
| ValueError | Wrong value |
| IndexError | Index out of range |
| KeyError | Dict key not found |
| FileNotFoundError | File doesn't exist |
Classes (OOP)
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi, {self.name}"
p = Person("Alice")
p.greet() # "Hi, Alice"