TechSchool
Home / Cheat sheets / Python

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

CodeWhat 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

CodeWhat it does
x = 5Store a whole number in a name.
pi = 3.14Store a decimal number in a name.
name = "Ana"Store text in a name.
ok = TrueStore a true or false value.
x = NoneStore an empty value.
a, b = 1, 2Assign two values in one line.
x = y = 0Give 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 xRemove a name from memory.

Strings

CodeWhat 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 sCheck if text contains a part.

Numbers and Math

CodeWhat it does
a + bAdd two numbers.
a - bSubtract one number from another.
a * bMultiply two numbers.
a / bDivide and get a decimal result.
a // bDivide and drop the remainder.
a % bGet the remainder of a division.
a ** 2Raise 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 mathLoad the math module for more tools.

Lists

CodeWhat 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 numsCheck if a value is in the list.

Conditions and Loops

CodeWhat 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.
breakStop the loop now.
continueSkip to the next loop step.
for i, v in enumerate(xs):Loop with index and value.

Functions

CodeWhat it does
def greet():Define a function with no inputs.
def add(a, b):Define a function with two inputs.
return a + bSend 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(): passMake an empty function body.
print(add.__name__)Show the name of a function.
help(add)Show help for a function.

Dictionaries and Files

CodeWhat 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"] = 2Add 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.
More on TechSchool
See the Python interview questions JavaScript TypeScript HTML CSS React Vue 3 Node.js Java PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures