Python cheat sheet
96 one-line examples for Python. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
Print and Input
| Code | What it does |
|---|---|
print("Hello") | Show text on the screen. |
print(42) | Show a number on the screen. |
print("a", "b") | Show two values with a space. |
print("a", end="") | Stop the line break after output. |
print("a", sep="-") | Set the separator between values. |
name = input("Name: ") | Read text from the user. |
age = int(input("Age: ")) | Read a number from the user. |
print(f"Hi {name}") | Put a variable inside text. |
print(f"{x:.2f}") | Show a number with two decimals. |
print(type(x)) | Show the type of a value. |
print(len(s)) | Show the length of a string. |
print("a\nb") | Print a new line inside text. |
Variables and Types
| Code | What it does |
|---|---|
x = 5 | Store a whole number in a name. |
pi = 3.14 | Store a decimal number in a name. |
name = "Ana" | Store text in a name. |
ok = True | Store a true or false value. |
x = None | Store an empty value. |
a, b = 1, 2 | Assign two values in one line. |
x = y = 0 | Give two names the same value. |
n = int("7") | Turn text into a whole number. |
f = float("2.5") | Turn text into a decimal number. |
s = str(99) | Turn a number into text. |
b = bool(0) | Turn a value into true or false. |
del x | Remove a name from memory. |
Strings
| Code | What it does |
|---|---|
s = "hello" | Make a string value. |
s[0] | Get the first character. |
s[-1] | Get the last character. |
s[1:4] | Get a part of the string. |
len(s) | Count the characters in a string. |
s.upper() | Make all letters uppercase. |
s.lower() | Make all letters lowercase. |
s.strip() | Remove spaces at both ends. |
s.replace("l", "L") | Swap one part of the text. |
s.split(",") | Cut text into a list. |
"-".join(parts) | Join a list into one string. |
"ell" in s | Check if text contains a part. |
Numbers and Math
| Code | What it does |
|---|---|
a + b | Add two numbers. |
a - b | Subtract one number from another. |
a * b | Multiply two numbers. |
a / b | Divide and get a decimal result. |
a // b | Divide and drop the remainder. |
a % b | Get the remainder of a division. |
a ** 2 | Raise a number to a power. |
abs(-3) | Get the value without a sign. |
round(2.567, 2) | Round a number to two decimals. |
max(3, 8, 1) | Get the largest number. |
min(3, 8, 1) | Get the smallest number. |
import math | Load the math module for more tools. |
Lists
| Code | What it does |
|---|---|
nums = [1, 2, 3] | Make a list of values. |
nums[0] | Get the first item. |
nums[-1] | Get the last item. |
nums[1:3] | Get a slice of the list. |
nums.append(4) | Add one item to the end. |
nums.insert(0, 9) | Add an item at a position. |
nums.remove(2) | Delete the first matching item. |
nums.pop() | Remove and return the last item. |
nums.sort() | Sort the list in place. |
sorted(nums) | Return a new sorted list. |
len(nums) | Count the items in a list. |
3 in nums | Check if a value is in the list. |
Conditions and Loops
| Code | What it does |
|---|---|
if x > 0: | Run a block when a test is true. |
elif x == 0: | Test another case. |
else: | Run a block when no test is true. |
if a and b: | Both tests must be true. |
if a or b: | One test must be true. |
if not done: | Reverse a true or false value. |
for i in range(5): | Repeat a block five times. |
for x in items: | Loop over each item. |
while x < 10: | Repeat while a test is true. |
break | Stop the loop now. |
continue | Skip to the next loop step. |
for i, v in enumerate(xs): | Loop with index and value. |
Functions
| Code | What it does |
|---|---|
def greet(): | Define a function with no inputs. |
def add(a, b): | Define a function with two inputs. |
return a + b | Send a value back to the caller. |
def f(x=0): | Give an input a default value. |
add(2, 3) | Call a function with two values. |
add(a=2, b=3) | Call a function with named values. |
def f(*args): | Accept any number of values. |
def f(**kw): | Accept any number of named values. |
result = add(1, 2) | Store the returned value. |
def f():
pass | Make an empty function body. |
print(add.__name__) | Show the name of a function. |
help(add) | Show help for a function. |
Dictionaries and Files
| Code | What it does |
|---|---|
d = {"a": 1} | Make a dictionary with one pair. |
d["a"] | Get a value by its key. |
d.get("b", 0) | Get a value or a default. |
d["b"] = 2 | Add or change a key value. |
del d["a"] | Remove a key and its value. |
d.keys() | Get all keys of a dictionary. |
d.values() | Get all values of a dictionary. |
d.items() | Get all key and value pairs. |
for k, v in d.items(): | Loop over keys and values. |
f = open("a.txt") | Open a file for reading. |
text = f.read() | Read the whole file. |
with open("a.txt") as f: | Open a file and close it later. |