Python 2b – Inputting Numbers

Convert keyboard input to whole numbers with int() or decimals with float().

Inputting Whole Numbers

Keyboard input arrives as text. To use it as a whole number, wrap input() with int():

age = int(input("How old are you? "))
print("Have you really lived for", age, "years?")

Example run:

How old are you? 99
Have you really lived for 99 years?

Inputting Numbers Task 1 – Zoo Visits

Ask how many times the user has been to the zoo, convert the answer to an integer, then print a sentence using the number.

zoo_visits = int(input("How many times have you been to the zoo? "))
print("You've been to the zoo", zoo_visits, "times? I love animals!")

Inputting Decimal Numbers

For values with a decimal point, use float() instead:

miles = float(input("How far have you walked today? "))
print("You really walked", miles, "miles? Wow!")

If the user enters 5.6, the printout confirms the distance.

Inputting Numbers Task 2 – Height

Ask for height in metres as a float, then print it in a sentence.

height = float(input("What is your height in metres? "))
print("You are", height, "metres tall? Wow!")