the full guide

Casting: changing types

Turn text into numbers and numbers into text, and fix the most common beginner error.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

Why you need it

Data often arrives as text, even when it looks like a number. Before doing maths, convert it.

casting.py
age_text = "14"

print(age_text + "1")       # Text: joins
print(int(age_text) + 1)    # Number: adds

print(float("3.5"))         # Text to decimal
print(int(3.9))             # Drops the decimal, doesn't round
print(str(100) + " marks")  # Number to text
print(round(3.9))           # This one rounds

Output

141
15
3.5
3
100 marks
4
FunctionTurns it into
int()A whole number
float()A decimal number
str()Text
bool()True or False

Asking the user: input()

On your own computer, input("Your age? ") waits for someone to type, and always gives you back text. That's why you'll often see int(input(...)). The examples on this site set the value directly, so each one runs with a single click.

Code challenge

marks = "78". Add 5 and print the result as a number.

print(int(marks) + 5) gives 83.

Finished reading?