Skip to content
Brainlag
  1. Reference
  2. Cheatsheets
  3. Python

Python cheatsheet

The Python you reach for most, from printing and strings to dicts, functions, errors, files and classes, one short line at a time.

Basics

print("Score:", score)

print adds spaces between values and a new line.

name = input("Name? ")

input always gives back a string, even for digits.

age = int(text)
price = float(text)

Turn text into a whole number or a decimal.

1 more: comments
# a comment

Python ignores everything after a hash.

Strings

f"{name} has {hp} HP"

An f-string puts values inside text.

s.split(), " ".join(words)

Text to a list of words, and back to text.

s[0], s[-1], s[:3], len(s)

First character, last character, first three, length.

2 more: case and spaces, searching
s.upper(), s.lower(), s.strip()

Change case, trim spaces. Each returns a new string.

"gg" in message

True if the text appears anywhere in the string.

Numbers

7 / 2, 7 // 2, 7 % 2

3.5, then whole number division (3), then remainder (1).

round(3.14159, 2)

Rounds to 2 decimal places: 3.14.

2 more: powers, showing 2 decimal places
2 ** 10

Powers: 2 to the 10th is 1024.

f"{price:.2f}"

Show a number with exactly 2 decimal places.

Conditions

if hp <= 0:
    print("Game over")
elif hp < 20:
    print("Low HP")
else:
    print("Fine")

Runs the first branch whose condition is true.

==, !=, <, <=, >, >=

One = stores, two == compares.

1 more: combining with and, or, not
if age >= 13 and not banned:

Combine conditions with and, or, not.

Loops

for song in playlist:
    print(song)

Runs once per item.

for i in range(1, 11):

The numbers 1 to 10. The end number is left out.

while lives > 0:

Repeats as long as the condition is true.

2 more: position and item, break and continue
for i, song in enumerate(playlist):

Gives the position and the item together.

break, continue

Leave the loop now, or skip to the next pass.

Lists

squad = ["Ana", "Ben"]
squad.append("Cleo")

Make a list and add to the end.

squad[0], squad[-1], squad[1:3]

First item, last item, a slice.

sum(scores), max(scores), len(scores)

Total, biggest, count.

2 more: removing, sorting
squad.remove("Ben"), squad.pop()

Remove by value, or remove and return the last item.

sorted(scores), scores.sort()

A new sorted list, or sort in place (which returns None).

Dictionaries

stock = {"potion": 3, "arrow": 20}

Keys on the left of each colon, values on the right.

stock["gem"] = 1

Add a key, or replace its value.

for item, n in stock.items():

Loop over keys and values together.

2 more: reading safely, checking a key
stock.get("shield", 0)

Read a key with a fallback instead of a KeyError.

"potion" in stock

Checks the keys.

Functions

def area(w, h):
    return w * h

Parameters in, one value back out with return.

def greet(name, loud=False):

A default value makes that argument optional.

total = area(3, 4)

Catch what comes back. With no return you get None.

1 more: passing by name
greet("Ana", loud=True)

Pass an argument by name.

Locked

Errors

Code 4 rows

Files and JSON

Code 5 rows

Classes

Code 4 rows