Lessons / Python / Unit 1

Values and variables

A variable is a name for a value. In Python you make one just by giving it a value. There's no extra keyword.

Python · Unit 1 of 5 · about 4 minutes

Printing things out

print() shows a value on screen. Text goes in quotes. Numbers don't.

print("Hello")
print(2 + 3)
Hello
5

Making a variable

Write a name, an = sign and a value. The = means "store this value under that name". To change it later, store a new value the same way.

age = 14
print(age)

age = 15
print(age)
14
15

Variable names can't have spaces. Python programmers usually join words with underscores, like high_score.

Try it

What does this print?

x = 10
x = x * 2
print(x)
The right side runs first. x is 10, so x * 2 is 20, and that gets stored back in x.

Numbers and strings

Text in quotes is called a string. + adds numbers, but joins strings. Unlike JavaScript, Python won't mix the two for you. It stops with an error instead.

print(2 + 3)
print("2" + "3")
print("2" + 3)
5
23
TypeError: can only concatenate str (not "int") to str

To join a number onto text, turn it into a string first with str(). To turn text into a number, use int().

print("Score: " + str(30))
print(int("4") + 1)
Score: 30
5

Try it

What does this print?

print("4" + "4")
Both sides are strings, so + joins them into 44.

Putting values inside text

An f-string lets you drop variables straight into text. Put an f before the opening quote and the variable in curly braces.

name = "Sam"
points = 30
print(f"{name} has {points} points")
Sam has 30 points

Checking the type

type() tells you what kind of value something is. int means a whole number and str means a string.

print(type(42))
print(type("42"))
<class 'int'>
<class 'str'>

Try it

What happens when this runs?

print("Age: " + 15)
You can't join a string and a number with +. Use str(15) or an f-string instead.

Common mistakes

Mixing strings and numbers

"Total: " + 5 gives a TypeError. Use str(5) or f"Total: {5}".

Capital letters in the wrong place

Python cares about case. Print("hi") gives NameError: name 'Print' is not defined.

Forgetting the quotes

name = Sam makes Python look for a variable called Sam, which gives a NameError.

Recap

  • print() shows a value.
  • You make a variable by giving it a value with =.
  • + adds numbers and joins strings, but won't mix them.
  • str() and int() convert between text and numbers.