Free Handbook · Runs in your browser

Fundamentals

Variables, literals and types; converting between them; input and output; every operator and the order they run in; and the two errors that end most first days — NameError and TypeError.

0 / 108 lessons🔥 0 day streak
ShareXLinkedIn

Module 01 · what you'll be able to do

  • Create variables of every basic type and check a type with type()
  • Convert between str, int, float and bool — and know when it fails
  • Read input, format output with f-strings, and control print()
  • Use arithmetic, comparison and logical operators with the right precedence
  • Read and fix a NameError and a str + int TypeError from the traceback
01

Variables, literals and types

A literal is a value written directly in code: 42, 3.14, "hello", True. A variable is a name bound to a value. Python figures out the type from the literal — you never declare it — and type() tells you what it decided.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
42 is a int
19.99 is a float
'Ada' is a str
False is a bool
None is a NoneType
Your turn
Add a line big = 10 ** 100 and print its type. Python ints have no maximum size.
TypeLiteral examplesNotes
int0 -7 1_000_000 0xFFUnlimited size. Underscores are allowed for readability.
float3.14 2.0 1e-964-bit; 0.1 + 0.2 != 0.3. Use decimal for money.
str"hi" 'hi' """multi line"""Immutable Unicode text. Single and double quotes are identical.
boolTrue FalseCapitalised. A subclass of int: True + True == 2.
NoneNoneThe one "no value" object. Functions that return nothing return this.

A name can be rebound to a value of a different type at any time — Python is dynamically typed. That is convenient and also the source of half the TypeErrors you will see, which is why type hints (Module 09) exist.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
10 int
ten str
2 1
Error you will hit

NameError: name 'totl' is not defined

python
total = 5 + 7
print(totl)
Traceback (most recent call last):
  File "your code", line 2, in <module>
    print(totl)
NameError: name 'totl' is not defined. Did you mean: 'total'?
Why the interpreter said that

The interpreter looked up the name totl and no such name has ever been bound. Ninety percent of NameErrors are a typo, a variable used before the line that creates it, or a name created inside a function and used outside it (scope — Module 04). Python 3.10+ even suggests the closest match.

The fix

Read the name in the error, then find where you meant to create it. Here it is a typo.

python
total = 5 + 7
print(total)
02

Type conversion

Python never silently turns a string into a number. You convert explicitly with the type's name as a function: int("42"), float("2.5"), str(42). This is deliberate — the alternative (JavaScript's "5" + 1 == "51") hides bugs.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
30
291
7.0
3
4 2
255 items
255 0b1010
Your turn
Try int("3.5"). It raises a ValueError — int parses whole numbers only. Convert via int(float("3.5")).

Truthiness — everything converts to bool

Every value is either truthy or falsy when used where a condition is expected. The falsy values are the "empty" ones; everything else is truthy. This is why if items: is the Pythonic way to ask "is the list non-empty".

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
[False, False, False, False, False, False, False, False]
[True, True, True, True, True, True, True]
The classic trap
"0" and "False" are non-empty strings, so they are truthy. bool(input("yes or no? ")) is always True. Compare the text instead: answer == "yes".
Quick check

What does int("7") + int("3") print, and what does "7" + "3" print?

03

Input and output

print() writes to the screen; input() reads a line typed by the user — always as a string, even if they typed digits. The editor on this page has no keyboard to read from, so input() raises here; on your machine it waits for you to type.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
Hello Ada
Hello, Ada
no newline | same line
Ada knows 3 languages
3.14
1,234,567
25.6%
       Ada|Ada       |   Ada    |
langs=3
Your turn
Print a receipt line: item name left-aligned in 12 characters, price right-aligned in 8 with two decimals.
pythongreet.py — run this one on your machine
name = input("What is your name? ")
age = int(input("How old are you? "))   # convert! input() returns str
print(f"Hi {name}. Next year you will be {age + 1}.")

Forgetting the int() around input() is the number-one first-day bug — you get TypeError: can only concatenate str (not "int") to str at age + 1.

stdout / stdin
Standard output and input: the two text streams every program has. print writes to stdout, input reads stdin. When you pipe programs together in a shell, one's stdout becomes the next one's stdin.
Format spec
The part after the colon in {value:spec}. .2f = 2 decimal places, , = thousands separators, >10 = right-align in 10, % = percentage.
04

Operators

Arithmetic first. Two of these surprise people from other languages: / always gives a float, and // is floor division — it rounds down, so -7 // 2 is -4, not -3.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
9 5 14
3.5
3 -4
1 1
1024
2.0
3
Your turn
Use // and % to split 125 minutes into hours and minutes.

Comparison and logical operators

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
True False True True
True
True
True
True
default
0
True False
True True True
== versus is
== asks "equal value?"; is asks "the very same object?". Use is only for None, True and False. a is b on two equal strings or ints may be True or False depending on caching — a bug that appears only in production.
Error you will hit

TypeError: can only concatenate str (not "int") to str

python
score = 42
print("Score: " + score)
Traceback (most recent call last):
  File "your code", line 2, in <module>
    print("Score: " + score)
TypeError: can only concatenate str (not "int") to str
Why the interpreter said that

The left side of + is a str, so Python tries string concatenation, and the right side is not a string. Python refuses to guess whether you wanted "Score: 42" or an addition. The same error appears as unsupported operand type(s) for +: 'int' and 'str' when the int is on the left.

The fix

Either convert with str(score) or — better — use an f-string, which converts everything for you.

python
score = 42
print(f"Score: {score}")
print("Score: " + str(score))   # also fine
05

Precedence and associativity

When an expression has several operators, precedence decides which runs first and associativity decides the order among equals. You know most of it from school: ** beats * beats +. The ones that bite are not, - before **, and comparisons versus and/or.

Precedence (high → low)OperatorsAssociativity
1() grouping, f(x) call, a[i] index, a.b attributeleft
2**right
3+x -x ~x unary
4* / // %left
5+ -left
6< <= > >= == != in ischained
7not
8andleft
9orleft
pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
14
20
512
-4
4
True
True
3
Your turn
Predict print(3 > 2 > 1, 3 > 2 == True) before running. The second one is a famous puzzle: it chains to 3 > 2 and 2 == True.
The rule that avoids all of this
When in doubt, add parentheses. They cost nothing and every reader (including you next month) stops having to remember the table.
06

Keywords and identifiers

An identifier is a name you choose: variables, functions, classes. A keyword is a name Python has reserved — if, for, def, class, None — and you cannot use them as identifiers. There are 35 of them; the list is always available from the keyword module.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
35 keywords
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
True False
  • Identifiers start with a letter or underscore, then letters, digits or underscores: total, _cache, user2. Not 2user, not my-var.
  • Case matters: Total, total and TOTAL are three names.
  • Convention (PEP 8): snake_case for variables and functions, PascalCase for classes, UPPER_CASE for constants, a leading _ for "internal".
  • Do not shadow built-ins. list = [1, 2] is legal and then list("abc") breaks with TypeError: 'list' object is not callable — a confusing error that Module 11 covers.
Error you will hit

SyntaxError: invalid syntax (a keyword used as a name)

python
class = "Python 101"
print(class)
  File "your code", line 1
    class = "Python 101"
          ^
SyntaxError: invalid syntax
Why the interpreter said that

class is a keyword, so the parser expected a class definition and found =. Note there is no "Traceback" header: a SyntaxError happens before the program runs at all, which is why the whole file fails even if the bad line is at the bottom.

The fix

Rename. The convention when you really want a reserved word is a trailing underscore.

python
class_ = "Python 101"
print(class_)
Quick check

Which of these is a valid identifier?

Finish the Python handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.