24 Python Cheat Sheet with Examples and Tips
Quickly review essential Python syntax for variables, strings, collections, conditions, loops, functions, and errors with practical examples.
2026-10-20 ยท 4 min read
Keep this Python cheat sheet nearby when practicing the basics. It covers common syntax and small examples for variables, conditions, loops, collections, functions, and error handling.
Variables and basic types
Python assigns a type based on the value. Use clear names in snake_case.
name = "Mina" # str
age = 20 # int
price = 2.5 # float
is_learning = True # bool
nothing = None # no value
print(type(age)) # <class 'int'>
Convert between common types when needed:
age_text = "20"
age_number = int(age_text)
print(age_number + 1) # 21
input() returns text, so convert its result before doing arithmetic.
Operators
| Purpose | Operators | Example |
|---|---|---|
| Arithmetic | +, -, *, /, //, %, ** | 7 // 2 is 3 |
| Compare | ==, !=, <, >, <=, >= | age >= 18 |
| Logic | and, or, not | age >= 18 and has_id |
| Membership | in, not in | "a" in "cat" |
Use = to assign a value and == to compare values.
Strings
Strings are text. Use f-strings to include values:
name = "Mina"
print(f"Hello, {name}!")
Useful string operations:
message = " Hello Python "
print(message.strip()) # "Hello Python"
print(message.lower()) # " hello python "
print(message.replace("Python", "world"))
print("red,blue".split(",")) # ["red", "blue"]
String indexes start at 0; negative indexes count from the end:
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:3]) # Pyt
Conditions
Use if, elif, and else to choose which code to run. Indent each block consistently, usually with four spaces.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "Keep practicing"
print(grade)
For numeric ranges, chained comparisons are readable:
age = 20
is_adult = 18 <= age < 120
Lists and tuples
A list is an ordered, changeable collection. A tuple is ordered and immutable.
fruits = ["apple", "banana"]
fruits.append("orange")
fruits[0] = "pear"
print(fruits[0]) # pear
print(len(fruits)) # 3
coordinates = (10, 20)
Loop through values directly when you do not need their indexes:
for fruit in fruits:
print(fruit)
Dictionaries and sets
A dictionary maps unique keys to values. A set stores unique values.
person = {"name": "Mina", "age": 20}
print(person["name"])
print(person.get("city", "Unknown"))
for key, value in person.items():
print(f"{key}: {value}")
unique_numbers = {1, 2, 2, 3}
print(unique_numbers) # {1, 2, 3}
Use dictionary[key] when the key is required. Use .get() when it may be missing.
Loops and comprehensions
range() stops before its end value. enumerate() gives both an index and item:
for number in range(1, 4):
print(number) # 1, 2, 3
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
A list comprehension is useful for a simple transformation:
squares = [number ** 2 for number in range(1, 5)]
print(squares) # [1, 4, 9, 16]
Use a regular loop when the logic becomes difficult to read.
Functions
Define reusable code with def. Use return to give a result back to the caller:
def greet(name):
return f"Hello, {name}!"
message = greet("Mina")
print(message)
Provide a default for an optional parameter:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Dara", "Good morning"))
Exceptions and files
Catch specific exceptions you know how to handle:
text = "42"
try:
number = int(text)
except ValueError:
print("Enter a whole number.")
else:
print(number)
Use with to work with a file so it is closed automatically:
from pathlib import Path
path = Path("notes.txt")
path.write_text("Practice Python.\n", encoding="utf-8")
contents = path.read_text(encoding="utf-8")
print(contents)
Python tips
- Use descriptive
snake_casenames, such astotal_price. - Keep indentation consistent; indentation is part of Python syntax.
- Prefer f-strings to joining values into strings with
+. - Use
enumerate()for indexes andzip()for corresponding items. - Use
.get()for optional dictionary keys. - Split complex code into small functions with clear purposes.
- Read the final line of a traceback first for the exception type and message.
- Test one small change at a time, and avoid catching errors you cannot handle.