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)
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")
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)
Common mistakes
"Total: " + 5 gives a TypeError. Use str(5) or f"Total: {5}".
Python cares about case. Print("hi") gives NameError: name 'Print' is not defined.
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.