Type casting is the process of converting one data type to another. Data Types in Python ended with a crash: "5" + 5 throws an error because Python refuses to guess whether you meant a number or text. So how do you actually fix that instead of just avoiding it?
You convert the type yourself, on purpose. That’s the whole idea behind type conversion, and once you start taking input from a user, you’ll use it in almost every program you write, because input() hands you a string every single time, even if someone types 25.
int(), float(), str(): the three you’ll use daily
a = "10"
b = int(a)
print(b + 5) # 15x = 5
y = float(x)
print(y) # 5.0age = 16
message = "I am " + str(age) + " years old"
print(message)That last example is the one people actually get stuck on. Write "I am " + age and Python stops you cold, string plus int doesn’t work with +. Wrap age in str() and the error disappears.
Where this bites everyone: input()
age = input("Enter your age: ")
print(type(age))Type 16 at that prompt and Python still reports <class 'str'>. Not a bug, just how input() works. Fix it by converting right away:
age = int(input("Enter your age: "))
next_year = age + 1
print("Next year you'll be", next_year)Drop the int() there and you get the exact same TypeError from the last lesson, just wearing a different outfit.
Practice Questions
- What does
int("25")return, and what type is it? - This line fails:
print("Score: " + 90). Why, and how would you fix it? - What is the output of
int(9.99)? - Take a user’s name and age with
input(), then print: “Hi <name>, in 5 years you’ll be <age+5>.” - Running
int("twenty")gives an error. Which one, and why does it happen?
