Python Cheat Sheet
Use this Python cheat sheet as a quick reference for syntax, variables, data types, conditionals, loops, functions, collections, files, errors, modules, classes, virtual environments, and common patterns.
Basic Python Syntax
Python uses indentation to group code.
Learn Python on Mimo
Python
message = "Hello, Python"
print(message)
Syntax Basics
- Use indentation instead of curly braces.
- Use
#for single-line comments. - Use meaningful variable names.
- Python is case-sensitive, so
nameandNameare different variables. - Most Python files use the
.pyextension.
Run Python Code
Run a Python File
Bash
python app.py
On some systems, use:
Bash
python3 app.py
Check Python Version
Bash
python --version
Or:
Bash
python3 --version
Open the Python Shell
Bash
python
Exit the shell:
Python
exit()
Comments
Single-Line Comment
Python
# This is a comment
Inline Comment
Python
total = 100 # Starting balance
Multi-Line String Used as a Note
Python
"""
This text can span multiple lines.
Use real comments for normal code notes.
"""
Use comments to explain why something happens, not every obvious line.
Variables
Create Variables
Python
name = "Alex"
age = 28
is_active = True
Reassign Variables
Python
score = 10
score = 15
Multiple Assignment
Python
x, y, z = 1, 2, 3
Same Value for Multiple Variables
Python
a = b = c = 0
Naming Rules
- Use letters, numbers, and underscores.
- Do not start variable names with numbers.
- Use
snake_casefor normal variable names. - Avoid names that shadow built-ins, such as
list,str, orsum.
Data Types
String
Python
name = "Alex"
Integer
Python
age = 28
Float
Python
price = 19.99
Boolean
Python
is_logged_in = True
has_access = False
None
Python
selected_user = None
List
Python
languages = ["Python", "JavaScript", "SQL"]
Tuple
Python
point = (10, 20)
Dictionary
Python
user = {
"name": "Alex",
"age": 28
}
Set
Python
unique_tags = {"python", "web", "data"}
Check Types
Use type()
Python
value = 42
print(type(value))
Use isinstance()
Python
age = 28
if isinstance(age, int):
print("Age is an integer")
isinstance() works well when you need to check a value before using it.
Type Conversion
Convert to String
Python
age = 28
text = str(age)
Convert to Integer
Python
value = "42"
number = int(value)
Convert to Float
Python
price = "19.99"
price_number = float(price)
Convert to Boolean
Python
is_valid = bool("hello")
Convert to List
Python
letters = list("abc")
print(letters)
Strings
Create Strings
Python
single = 'Hello'
double = "Hello"
Multiline String
Python
message = """
Line one
Line two
"""
f-String
Python
name = "Alex"
message = f"Hello, {name}"
print(message)
String Length
Python
text = "Python"
print(len(text))
Change Case
Python
text = "Python"
print(text.lower())
print(text.upper())
print(text.title())
Remove Whitespace
Python
text = " hello "
print(text.strip())
Check Text
Python
title = "Learn Python"
print("Python" in title)
print(title.startswith("Learn"))
print(title.endswith("Python"))
Replace Text
Python
text = "I like Java"
new_text = text.replace("Java", "Python")
print(new_text)
Split and Join
Python
tags = "python,css,html"
tag_list = tags.split(",")
print(tag_list)
Python
words = ["Learn", "Python"]
sentence = " ".join(words)
print(sentence)
Numbers and Math
Basic Math
Python
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
Floor Division
Python
print(10 // 3)
Remainder
Python
print(10 % 3)
Power
Python
print(2 ** 3)
Round
Python
price = 19.987
print(round(price, 2))
Common Math Functions
Python
numbers = [5, 2, 9]
print(min(numbers))
print(max(numbers))
print(sum(numbers))
Operators
Comparison Operators
Python
print(10 == 10)
print(10 != 5)
print(10 > 5)
print(10 >= 10)
print(5 < 10)
print(5 <= 5)
Logical Operators
Python
is_adult = True
has_ticket = False
print(is_adult and has_ticket)
print(is_adult or has_ticket)
print(not is_adult)
Assignment Operators
Python
score = 10
score += 5
score -= 2
score *= 3
score /= 2
Membership Operators
Python
languages = ["Python", "JavaScript"]
print("Python" in languages)
print("Ruby" not in languages)
Conditionals
if
Python
age = 20
if age >= 18:
print("Adult")
if...else
Python
is_logged_in = False
if is_logged_in:
print("Welcome back")
else:
print("Please log in")
elif
Python
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("Keep practicing")
Ternary Expression
Python
age = 20
message = "Adult" if age >= 18 else "Minor"
print(message)
Use ternary expressions for short decisions. Use normal if...else blocks for longer logic.
Loops
for Loop
Python
languages = ["Python", "JavaScript", "SQL"]
for language in languages:
print(language)
range()
Python
for number in range(5):
print(number)
Start and stop:
Python
for number in range(1, 6):
print(number)
Step value:
Python
for number in range(0, 10, 2):
print(number)
while Loop
Python
count = 0
while count < 3:
print(count)
count += 1
break
Python
for number in range(10):
if number == 5:
break
print(number)
continue
Python
for number in range(5):
if number == 2:
continue
print(number)
Loop with Index
Python
names = ["Alex", "Sam", "Taylor"]
for index, name in enumerate(names):
print(index, name)
Lists
Create a List
Python
fruits = ["apple", "banana", "orange"]
Access Items
Python
print(fruits[0])
print(fruits[-1])
Change an Item
Python
fruits[1] = "mango"
Add Items
Python
fruits.append("grape")
fruits.insert(0, "kiwi")
Remove Items
Python
fruits.remove("apple")
last_fruit = fruits.pop()
List Length
Python
print(len(fruits))
Slice a List
Python
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
Sort a List
Python
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)
Create a sorted copy:
Python
numbers = [3, 1, 4, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
List Comprehensions
List comprehensions create lists in a compact way.
Python
numbers = [1, 2, 3, 4]
squares = [number ** 2 for number in numbers]
print(squares)
With a Condition
Python
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Use comprehensions for simple transformations. Use normal loops when logic becomes hard to read.
Tuples
Tuples are ordered and cannot be changed after creation.
Python
point = (10, 20)
print(point[0])
print(point[1])
Unpack a Tuple
Python
x, y = point
print(x)
print(y)
Use tuples for fixed groups of values, such as coordinates or pairs.
Dictionaries
Create a Dictionary
Python
user = {
"name": "Alex",
"age": 28,
"is_member": True
}
Access Values
Python
print(user["name"])
Safer access with get():
Python
print(user.get("email"))
print(user.get("email", "No email"))
Add or Update Values
Python
user["city"] = "Vienna"
user["age"] = 29
Remove Values
Python
user.pop("city")
Loop Through Keys and Values
Python
for key, value in user.items():
print(key, value)
Dictionary Comprehension
Python
numbers = [1, 2, 3]
squares = {number: number ** 2 for number in numbers}
print(squares)
Sets
Sets store unique values.
Python
tags = {"python", "web", "python"}
print(tags)
Add and Remove
Python
tags.add("data")
tags.remove("web")
Set Operations
Python
a = {"python", "html", "css"}
b = {"python", "sql"}
print(a | b)
print(a & b)
print(a - b)
Set Uses
- Remove duplicate values.
- Check membership quickly.
- Compare groups of values.
- Find shared or different items.
Functions
Define a Function
Python
def greet(name):
return f"Hello, {name}"
Call a Function
Python
message = greet("Alex")
print(message)
Default Parameter
Python
def greet(name="Guest"):
return f"Hello, {name}"
print(greet())
Keyword Arguments
Python
def create_user(name, age):
return {
"name": name,
"age": age
}
user = create_user(age=28, name="Alex")
print(user)
Return Multiple Values
Python
def get_coordinates():
return 10, 20
x, y = get_coordinates()
print(x, y)
Lambda Functions
A lambda is a small anonymous function.
Python
double = lambda number: number * 2
print(double(5))
Use lambda functions for short callbacks.
Python
users = [
{"name": "Alex", "age": 28},
{"name": "Sam", "age": 24}
]
users.sort(key=lambda user: user["age"])
print(users)
Use normal functions when the logic needs more than one simple expression.
Scope
Local Scope
Python
def show_message():
message = "Hello"
print(message)
show_message()
message only exists inside the function.
Global Scope
Python
count = 0
def show_count():
print(count)
show_count()
Avoid Unnecessary Globals
Python
def increment(count):
return count + 1
count = 0
count = increment(count)
print(count)
Passing values into functions is usually clearer than changing global variables.
Files
Read a File
Python
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Read Lines
Python
with open("notes.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
print(lines)
Write a File
Python
with open("result.txt", "w", encoding="utf-8") as file:
file.write("Task complete")
Append to a File
Python
with open("log.txt", "a", encoding="utf-8") as file:
file.write("New log entry\n")
Use with open(...) so Python closes the file automatically.
Paths
Use pathlib
Python
from pathlib import Path
current_directory = Path.cwd()
file_path = current_directory / "data.txt"
print(file_path)
Get the Script Folder
Python
from pathlib import Path
script_directory = Path(__file__).parent
config_file = script_directory / "config.json"
print(config_file)
Use Path.cwd() for the folder where Python is running. Use Path(__file__).parent for the folder that contains the script.
Error Handling
try...except
Python
try:
number = int("abc")
except ValueError:
print("Invalid number")
Catch Multiple Errors
Python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid value")
else and finally
Python
try:
number = int("42")
except ValueError:
print("Invalid number")
else:
print("Conversion worked")
finally:
print("Done")
Raise an Error
Python
def divide(a, b):
if b == 0:
raise ValueError("b cannot be zero")
return a / b
Imports and Modules
Import a Module
Python
import math
print(math.sqrt(16))
Import a Specific Function
Python
from math import sqrt
print(sqrt(16))
Import with an Alias
Python
import datetime as dt
today = dt.date.today()
print(today)
Create Your Own Module
Create a file named helpers.py.
Python
def greet(name):
return f"Hello, {name}"
Import it in another file.
Python
from helpers import greet
print(greet("Alex"))
Common Built-In Functions
Python
print("Hello")
Length
Python
print(len("Python"))
Range
Python
for number in range(3):
print(number)
Input
Python
name = input("Enter your name: ")
print(f"Hello, {name}")
Enumerate
Python
names = ["Alex", "Sam"]
for index, name in enumerate(names):
print(index, name)
Zip
Python
names = ["Alex", "Sam"]
scores = [90, 85]
for name, score in zip(names, scores):
print(name, score)
Map
Python
numbers = ["1", "2", "3"]
converted = list(map(int, numbers))
print(converted)
Filter
Python
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda number: number % 2 == 0, numbers))
print(even_numbers)
List comprehensions are often easier to read than map() or filter().
Classes
Create a Class
Python
class User:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}"
Create an Object
Python
user = User("Alex")
print(user.greet())
Instance Attributes
Python
class Product:
def __init__(self, title, price):
self.title = title
self.price = price
Inheritance
Python
class Animal:
def speak(self):
return "Sound"
class Dog(Animal):
def speak(self):
return "Bark"
dog = Dog()
print(dog.speak())
Use classes when you need to group data and behavior together.
Dataclasses
Dataclasses reduce boilerplate for simple data objects.
Python
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
user = User(name="Alex", age=28)
print(user)
Dataclasses are useful for models, configuration objects, and structured data.
Type Hints
Type hints make code easier to read and check.
Python
def greet(name: str) -> str:
return f"Hello, {name}"
Type Hints with Lists
Python
def total(numbers: list[int]) -> int:
return sum(numbers)
Type Hints with Dictionaries
Python
def get_username(user: dict[str, str]) -> str:
return user["name"]
Type hints do not change runtime behavior by themselves. They help editors, readers, and type checkers.
Virtual Environments
A virtual environment keeps project packages separate.
Create a Virtual Environment
Bash
python -m venv .venv
Activate on macOS or Linux
Bash
source .venv/bin/activate
Activate on Windows PowerShell
.venv\Scripts\Activate.ps1
Deactivate
Bash
deactivate
What to Look For
- Your terminal prompt may show
(.venv). - Packages install into the project environment.
- Use one virtual environment per project.
Packages with pip
Install a Package
Bash
pip install requests
List Installed Packages
Bash
pip list
Save Dependencies
Bash
pip freeze > requirements.txt
Install Dependencies
Bash
pip install -r requirements.txt
Use requirements.txt when sharing a project or deploying it.
Working with JSON
Convert Dictionary to JSON
Python
import json
user = {
"name": "Alex",
"age": 28
}
json_text = json.dumps(user)
print(json_text)
Convert JSON to Dictionary
Python
import json
json_text = '{"name": "Alex", "age": 28}'
user = json.loads(json_text)
print(user["name"])
Read JSON from a File
Python
import json
with open("user.json", "r", encoding="utf-8") as file:
user = json.load(file)
print(user)
Write JSON to a File
Python
import json
user = {
"name": "Alex",
"age": 28
}
with open("user.json", "w", encoding="utf-8") as file:
json.dump(user, file, indent=4)
Dates and Times
Current Date
Python
from datetime import date
today = date.today()
print(today)
Current Date and Time
Python
from datetime import datetime
now = datetime.now()
print(now)
Format a Date
Python
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d")
print(formatted)
Parse a Date String
Python
from datetime import datetime
date_text = "2026-06-23"
parsed_date = datetime.strptime(date_text, "%Y-%m-%d")
print(parsed_date)
Common Python Patterns
Count Items
Python
items = ["apple", "banana", "apple"]
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1
print(counts)
Find the Largest Item
Python
numbers = [10, 4, 25, 7]
largest = max(numbers)
print(largest)
Filter Data
Python
users = [
{"name": "Alex", "active": True},
{"name": "Sam", "active": False},
{"name": "Taylor", "active": True}
]
active_users = [user for user in users if user["active"]]
print(active_users)
Sort Dictionaries by a Value
Python
users = [
{"name": "Alex", "score": 90},
{"name": "Sam", "score": 85}
]
users.sort(key=lambda user: user["score"], reverse=True)
print(users)
Check If a File Exists
Python
from pathlib import Path
file_path = Path("data.txt")
if file_path.exists():
print("File exists")
else:
print("File missing")
Use main()
Python
def main():
print("Program started")
if __name__ == "__main__":
main()
This pattern makes your file easier to run and import.
Common Mistakes
Wrong Indentation
Python
if True:
print("Hello")
Better:
Python
if True:
print("Hello")
Python requires consistent indentation.
Using = Instead of ==
Python
if age = 18:
print("Adult")
Better:
Python
if age == 18:
print("Adult")
Use = for assignment and == for comparison.
Forgetting Quotes Around Strings
Python
name = Alex
Better:
Python
name = "Alex"
Without quotes, Python treats Alex as a variable name.
Modifying a List While Looping Over It
Python
numbers = [1, 2, 3, 4]
for number in numbers:
if number % 2 == 0:
numbers.remove(number)
Better:
Python
numbers = [1, 2, 3, 4]
numbers = [number for number in numbers if number % 2 != 0]
Create a new list when filtering.
Using Mutable Default Arguments
Python
def add_item(item, items=[]):
items.append(item)
return items
Better:
Python
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Use None as the default when the value should be created fresh each time.
Debugging Tips
Print Values
Python
print(user)
Print Labels
Python
print("Current user:", user)
Check Types
Python
print(type(value))
Use repr()
Python
text = "hello\n"
print(repr(text))
repr() helps reveal hidden characters.
Use the Debugger
Python
breakpoint()
Run the script, then inspect values when execution pauses.
Read Error Messages from the Bottom
The last line of a Python traceback usually tells you the error type and message.
Quick Reference
Print Output
Python
print("Hello")
Create a Variable
Python
name = "Alex"
Create a List
Python
items = ["one", "two", "three"]
Create a Dictionary
Python
user = {
"name": "Alex",
"age": 28
}
Write an if Statement
Python
if age >= 18:
print("Adult")
Write a Loop
Python
for item in items:
print(item)
Write a Function
Python
def greet(name):
return f"Hello, {name}"
Read a File
Python
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
Handle an Error
Python
try:
number = int(value)
except ValueError:
print("Invalid number")
Import a Module
Python
import math
Create a Class
Python
class User:
def __init__(self, name):
self.name = name
Create a Virtual Environment
Bash
python -m venv .venv
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot