Beginner Fundamentals

Type casting

Casting converts a value from one type to another with int(), float(), and str().

To integer

int(3.9)     # 3   (truncates, doesn't round)
int("10")    # 10

To float

float(5)       # 5.0
float("3.14")  # 3.14

To string

str(10)      # "10"
str(3.14)    # "3.14"

Common case: user input

input() always returns text. To do math, convert it:

age = input("Age: ")   # "30" (str)
age = int(age)         # 30 (int)
print(age + 1)         # 31

Without int(), age + 1 would error: you can’t add str and int.

Watch out

int("abc")   # ValueError: not a number