Strings and Integers
π¨π Technique Card: str and int in Python
π§ What Are str and int?
str
means string β it's text, like"hello"
or"5"
int
means integer β it's a whole number, like5
or42
name = "Alex" # str (text)
age = 10 # int (number)
Note
We use =
in Python to assign a value to a variable | for example "Alex"
is the value which is assigned to a variable we have called name
π§© Problem
You want to print:
β‘οΈ "Alex is 10 years old."
But this wonβt work:
print(name + " is " + age + " years old.")
β Youβll get an error! Why?
Because you canβt add (+
) a str
and an int
directly.
π οΈ 2 Ways to Fix It
β 1. Convert the number to a string
print(name + " is " + str(age) + " years old.")
π‘ Use str()
to turn a number into text.
β 2. Use an f-string (fancy and easy - it is the recomended solution!)
print(f"{name} is {age} years old.")
π‘ Put an f
before the string and use {}
to plug in values.
β¨ Try It!
favourite_number = 7
print("My favourite number is " + str(favourite_number)) # Method 1
print(f"My favourite number is {favourite_number}") # Method 2
π§ͺ Challenge!
Change the code so it says:
"Jordan is 12 years old and loves the number 8!"
π Tips
- Use
type()
to check if something is a string or an int
β e.g.,print(type(name))
π Deep Dive
You can find out more about str
and int
by checking out Technique Card: str and int in Python (deeper)