Skip to content

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, like 5 or 42
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)


Watch the video