Python cheat sheet
The syntax of the course on one page. Each part names the lesson that teaches it.
Print and comments
Lesson: Print a message
# A comment starts with a number sign.
print("Good morning!")
print('Two kinds of quotes work')
printshows a message on the screen.- A string is text in quotes.
- A line has no semicolon at the end. The end of the line ends the instruction.
Variables and types
Lesson: Variables and numbers
city = "Lisbon"
score = 10
score = 12 # a new value
final_score = 97 # lower case and underscores
| Type | Example | What it is |
|---|---|---|
str |
"Mars" |
text |
int |
42 |
a whole number |
float |
3.5 |
a number with decimals |
bool |
True |
True or False |
type(value) tells you the type of a value.
Math and f-strings
Lesson: Variables and numbers
| Operator | What it does | Example | Result |
|---|---|---|---|
+ - * |
add, subtract, multiply | 7 * 2 |
14 |
/ |
divide. The result is a float. | 7 / 2 |
3.5 |
// |
divide and drop the decimals | 7 // 2 |
3 |
% |
remainder | 7 % 2 |
1 |
** |
power | 7 ** 2 |
49 |
name = "Sam"
print(f"Hello, {name}!") # Hello, Sam!
print(f"The sum is {2 + 2}.") # The sum is 4.
An f-string has the letter f before the first quote. Braces put a value into the text.
Strings
Lesson: Working with text
A method gives a new string. It does not change the old one.
| Code | Result |
|---|---|
" hi ".strip() |
"hi" |
"Hello".lower() |
"hello" |
"hello".upper() |
"HELLO" |
"a quick fox".title() |
"A Quick Fox" |
"a-b-c".split("-") |
["a", "b", "c"] |
"a fox".replace("a", "the") |
"the fox" |
"hello".startswith("he") |
True |
len("python") |
6 |
"python"[0] |
"p" |
"python"[-1] |
"n" |
"python"[1:4] |
"yth" |
"th" in "python" |
True |
Positions start at 0. A slice stops before its end position.
Conditions
Lesson: Making decisions
if score >= 90:
print("Great")
elif score >= 50:
print("Pass")
else:
print("Try again")
- A line with
if,eliforelseends with a colon. - The block under it has an indent of four spaces.
- Python runs the first block whose condition is true.
| Operator | Meaning |
|---|---|
== |
is equal to |
!= |
is not equal to |
> < |
greater than, less than |
>= <= |
greater or equal, less or equal |
a and b |
true when the two sides are true |
a or b |
true when one side or the two sides are true |
not a |
True becomes False, False becomes True |
One = stores a value. Two == compare two values.
Loops
Lesson: Loops
for i in range(3):
print(i) # 0, 1, 2
n = 3
while n > 0:
print(n) # 3, 2, 1
n -= 1 # without it, the loop never ends
total = 0
for i in range(1, 4):
total += i # the same as total = total + i
print(total) # 6
| Code | Numbers |
|---|---|
range(4) |
0, 1, 2, 3 |
range(1, 4) |
1, 2, 3 |
range(0, 10, 3) |
0, 3, 6, 9 |
The end number is not included. To join a number to text, use str(3) or an f-string.
Lists
Lesson: Lists
colors = ["red", "green", "blue"]
print(colors[0]) # red
print(colors[-1]) # blue, the last item
print(len(colors)) # 3
print(colors[0:2]) # ['red', 'green']
for color in colors:
print(color)
| Code | What it does |
|---|---|
colors.append("pink") |
adds an item to the end |
colors.pop() |
removes the last item and gives it back |
colors.remove("red") |
removes the first item that matches |
colors.sort() |
puts the items in order |
"red" in colors |
True when the item is in the list |
", ".join(colors) |
one string from all text items |
sum([10, 7, 9]) |
adds the numbers of a list |
A list can change. A method such as append changes the list that you have.
Dictionaries
Lesson: Dictionaries
pet = {"name": "Biscuit", "age": 4}
print(pet["name"]) # Biscuit
pet["age"] = 5 # change a value
pet["color"] = "brown" # add a pair
print(pet.get("weight")) # None
print(pet.get("weight", 0)) # 0
print("name" in pet) # True
print(len(pet)) # 3
for key, value in pet.items():
print(key, value)
pet["weight"]stops with aKeyErrorwhen the key does not exist.getdoes not.pet.keys()gives the keys, andpet.values()gives the values.
A list of dictionaries
pets = [
{"name": "Biscuit", "age": 4},
{"name": "Pepper", "age": 2},
]
for pet in pets:
print(pet["name"], "is", pet["age"])
Functions
Lesson: Functions
def add(a, b): # a and b are parameters
return a + b
print(add(2, 3)) # 5. 2 and 3 are arguments.
def welcome(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(welcome("Sam")) # Hello, Sam!
print(welcome("Sam", "Hi")) # Hi, Sam!
returngives a value back to the code that called the function, and it stops the function.printshows a value to a person. A function that only prints gives backNone.- A parameter with a default value goes after the parameters without one.
f"{value:.1f}"puts a number into text with one digit after the decimal point.