LESSON 07
Type Conversion
Python thinks your age is text. Time to set it straight.
USES: print( ), variables, strings, numbers, f-strings, input( ).
01
Three kinds of data
You have met three kinds of values: "hello" is a string (str), text. 25 is an integer (int), a whole number. 4.5 is a float, a number with decimals. type( ) tells you which one you have. "25" and 25 look almost the same, but to Python they are different things. That is why input( ) caused trouble last lesson: it hands you "25", the text, when you wanted 25, the number.
BLUEPRINT ยท TAP OR HOVER EACH PIECE
Blueprint 1 of 1: the conversion. Tap each piece.
02
int( ): text to whole number
int( ) converts text that looks like a whole number into a real number. This is last lesson's crash, fixed: the answer arrives as text, int( ) turns it into a number, and only then does the maths happen. The same wrap fixes the 53: two converted answers add instead of gluing.
03
When int( ) refuses
int( ) cannot turn "hello" into a number, and it says so with a ValueError. That is reasonable: there is no number hiding in that text. For now just type valid numbers. There is a proper way to handle bad input, and it comes in a later lesson.
04
float( ): text to decimal
For numbers that might have decimals, use float( ). Watch out: int( ) cannot handle text with a decimal point, even though 4.5 is a number. Rule of thumb: if the value might have decimals (a price, a height), use float( ). If it is always whole (an age, a quantity), use int( ).
05
str( ): number to text
The reverse also exists. str( ) turns a number into text. len( ) only works on text, and str(12345) is the text "12345", which has 5 characters. Older tutorials use str( ) to glue numbers into sentences. It works, but you already have f-strings, which are cleaner and need no conversion at all.
06
Quick quiz: which line works?
The person types 4.5 into x. Which line turns it into a number without crashing?