Python Basics
Everything introduced in the first course, on one page.
Output
| Code | Result |
|---|---|
print("hi") | prints hi and a newline |
print("a", "b") | a b — comma inserts a space |
print("a", end="") | no newline at the end |
Variables
name = "Ada" # str
age = 36 # int
height = 1.7 # float
is_active = True # bool
nothing = None # NoneType
Names use snake_case, may contain letters, digits and underscores, and cannot start
with a digit.
score = 0
score += 10 # same as score = score + 10
score -= 3 # also -=, *=, /=
Strings
| Operation | Example | Result |
|---|---|---|
| join | "Ada" + " " + "L" | "Ada L" |
| repeat | "ab" * 3 | "ababab" |
| length | len("Ada") | 3 |
| case | "Ada".upper() | "ADA" |
| case | "Ada".lower() | "ada" |
| trim | " hi ".strip() | "hi" |
| split | "a,b".split(",") | ["a", "b"] |
| join list | ",".join(["a", "b"]) | "a,b" |
| replace | "cat".replace("c", "b") | "bat" |
| contains | "a" in "cat" | True |
f-strings
f"{name} is {age}" # values dropped in
f"{price:.2f}" # two decimal places
f"{age + 1}" # any expression
Numbers
| Operator | Meaning | Example |
|---|---|---|
+ - * | add, subtract, multiply | 3 * 4 → 12 |
/ | divide — always a float | 7 / 2 → 3.5 |
// | floor divide | 7 // 2 → 3 |
% | remainder | 7 % 2 → 1 |
** | power | 2 ** 10 → 1024 |
int("5") # 5
float("2.5") # 2.5
str(5) # "5"
round(3.14159, 2) # 3.14
abs(-4) # 4
Input
name = input("Name: ") # always a string
age = int(input("Age: ")) # convert to use as a number
Comparisons and booleans
| Operator | Question |
|---|---|
== | equal? |
!= | different? |
< > <= >= | ordering |
in | is it contained? |
is | the same object? (use for None) |
Falsy values: 0, 0.0, "", [], {}, (), None.
Everything else is truthy.
a and b # both
a or b # either
not a # invert
13 <= age <= 19 # chained comparison
and binds tighter than or — use brackets when mixing them.
Decisions
if score >= 70:
grade = "A"
elif score >= 50:
grade = "B"
else:
grade = "C"
The colon ends the condition; the indentation is the block. Python takes the first matching branch and skips the rest, so order from most to least specific.
Loops
for i in range(5): # 0 1 2 3 4
for i in range(2, 6): # 2 3 4 5
for i in range(0, 10, 2): # 0 2 4 6 8
for letter in "cat": # c a t
for item in items: # each value
while count > 0:
count -= 1 # something must change, or it never ends
| Keyword | Effect |
|---|---|
break | leave the loop entirely |
continue | skip to the next pass |
Functions
def grade(score):
if score >= 70:
return "A"
return "B"
return hands a value back and stops the function. A function with no return
gives back None. print shows a value; return gives it to the caller — they are
not the same thing.
FizzBuzz, for reference
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Test the most specific case first, or 15 comes out as "Fizz".
Common errors
| Error | Usual cause |
|---|---|
SyntaxError | missing colon, bracket or quote |
IndentationError | inconsistent indentation |
NameError | using a name before creating it, or a typo |
TypeError | "5" + 1 — convert first |
ValueError | int("abc") |
ZeroDivisionError | dividing by zero |