Types and conversion
Why "5" + "5" is "55", and how int() and float() fix it.
Code runs right here in your browser. Nothing to install.
Learn it
input() always gives a string, so convert with int() or float() before doing maths.
Every value in Python has a type. 7 is an int, 7.5 is a float, "7" is a str (string) and True is a bool. The type() function tells you which: type(7.5) gives <class 'float'>.
Here is the catch: input() always gives you a string, even if the user types a number. "5" + "5" joins text to make "55". To do maths, convert first with int() or float(): age = int(input("Age? ")).
To go the other way, str(42) turns a number into text so you can join it with +. Converting text that is not a number, like int("hello"), causes a ValueError.
print(type(7), type(7.5), type("7"), type(True)) print("5" + "5") print(int("5") + int("5")) age = int("14") print("Next year you will be " + str(age + 1))
Try it yourself
+10 XPAsk the user for their age. Convert it to a number and print Next year you will be 15 (for an answer of 14).
Create a free account to start this lab
Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.
Capture the flag
+10 XPWhat type of value does input() always give back? (three letters)
Create a free account to start this lab
Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.
Two-number calculator
+20 XPAsk for two numbers (they may have decimals, so use float()). Print their sum, difference, product and quotient, each on its own line with a label, like Sum: 9.5.
Create a free account to start this lab
Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.