- Library
- Cheatsheets
- 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 puts a space between values and a new line at the end.
name = input("Name? ")input always gives back a string, even when someone types digits.
age = int(text)
price = float(text)Turn text into a whole number or a decimal.
# a commentPython ignores everything after a hash.
Strings
f"{name} has {hp} HP"An f-string puts values inside text.
s.upper(), s.lower(), s.strip()Change case, trim spaces. Each method returns a new string.
s.split(), " ".join(words)Text to a list of words, and a list of words back to text.
s[0], s[-1], s[:3], len(s)First character, last character, first three, length.
"gg" in messageTrue if the text appears anywhere in the string.
Numbers
7 / 2, 7 // 2, 7 % 23.5, then whole number division (3), then the remainder (1).
2 ** 10Powers: 2 to the 10th is 1024.
round(3.14159, 2)Rounds to 2 decimal places: 3.14.
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")Python checks each condition in order and runs the first one that is true.
==, !=, <, <=, >, >=Compare values. One = stores, two == compares.
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.
for i, song in enumerate(playlist):Gives the position and the item together.
while lives > 0:Repeats as long as the condition is true.
break, continueLeave 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.
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 this list in place (which returns None).
sum(scores), max(scores), len(scores)Total, biggest, count.
Dictionaries
stock = {"potion": 3, "arrow": 20}Keys on the left of each colon, values on the right.
stock["gem"] = 1Add a key, or replace its value.
stock.get("shield", 0)Read a key with a fallback instead of a KeyError.
for item, n in stock.items():Loop over keys and values together.
"potion" in stockChecks the keys.
Functions
def area(w, h):
return w * hParameters in, one value back out with return.
def greet(name, loud=False):A default value makes that argument optional.
greet("Ana", loud=True)Pass an argument by name.
total = area(3, 4)Catch what a function returns. With no return you get None.
Errors
Premium 4 rows
Files and JSON
Premium 5 rows
Classes
Premium 4 rows
Premium The three marked sections come with Premium. See Premium