Type conversion means making a value of one type from a value of another type, for example the number 42 from the text "42". Python does this when you call the type's name as a function: int(), float(), str() or bool().
The program
print(int("42") + 1) print(float("3.5") * 2) print(str(7) + " days") print(int(9.99)) print(int(-9.99)) print(float(5)) print(bool(0), bool(3), bool(""), bool("no"))
43 7.0 7 days 9 -9 5.0 False True False True
How it works
int("42")reads text as a whole number.float("3.5")reads text as a number with a decimal point.str(7)turns a number into text, so it can be joined to other text with+.int()on a float removes the decimal part. It does not round:int(9.99)is 9, andint(-9.99)is -9.bool()givesFalsefor 0, 0.0,Noneand empty containers such as"",[]and{}, andTruefor almost everything else. Sobool("no")and evenbool("False")areTrue, because the string is not empty.
What fails
int() accepts only text that looks like a whole number. Spaces at the start and end are allowed, but a decimal point, a comma or a word is not:
for text in ["42", " 42 ", "3.5", "4,000", "seven"]: try: print(repr(text), "->", int(text)) except ValueError as error: print(repr(text), "-> ValueError:", error)
'42' -> 42 ' 42 ' -> 42 '3.5' -> ValueError: invalid literal for int() with base 10: '3.5' '4,000' -> ValueError: invalid literal for int() with base 10: '4,000' 'seven' -> ValueError: invalid literal for int() with base 10: 'seven'
To get a whole number from "3.5", convert in two steps, and remove the comma from "4,000" first:
print(int(float("3.5"))) print(int("4,000".replace(",", "")))
3 4000
int(float(...)) cuts off the decimal part. Use round(float(text)) if you want the nearest whole number instead. Other failing conversions: float("abc") raises ValueError, and int(None) raises TypeError. The ValueError page shows how to keep asking until the user types a valid number.