Browser lab15 min+60 XP

Types and conversion

Why "5" + "5" is "55", and how int() and float() fix it.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

input() always gives a string, so convert with int() or float() before doing maths.

Key words
7intwhole number7.5floatdecimal"7"strtextTrueboolTrue or False"14"str from input()14int15intint()+ 1
Four common types, and converting text into a number.

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.

Real life linkType your age into a web form and it arrives as text. The site has to convert it to a number before it can check you are old enough.
Example code
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))
TASK 2

Try it yourself

+10 XP

Ask 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.

TASK 3

Capture the flag

+10 XP

What 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.

HOMEWORK

Two-number calculator

+20 XP

Ask 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.