Python Arena
Step 4 of 5

Numbers as input

input always gives a string, even when the user types digits. Calculating with that string as if it were a number fails:

guests = input("Guests: ")
print(guests + 2)
Input
8
Output
Guests: 8
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(guests + 2)
          ~~~~~~~^~~
TypeError: can only concatenate str (not "int") to str

The user typed 8, but guests holds the string "8". With a string on its left, + means joining, and Python can't join a number to a string.

int and float

You converted numbers into strings with str. The functions int and float go the other way: int("8") is the integer 8, and float("2.5") is the float 2.5.

answer = input("Guests: ")
guests = int(answer)
print(f"Put out {guests + 2} chairs: one for each guest and two spare.")
Input
8
Output
Guests: 8
Put out 10 chairs: one for each guest and two spare.

Programs usually do the reading and the converting in one line, with input inside the parentheses of int. Python works from the inside out: it runs input first and hands the string it gets to int:

dog_age = int(input("Dog's age in years: "))
print(f"That's about {dog_age * 7} in human years.")
Input
3
Output
Dog's age in years: 3
That's about 21 in human years.

When the number may have decimals, use float instead:

price = float(input("Price: "))
print(f"With a 20% discount: {price * 0.8}")
Input
12.5
Output
Price: 12.5
With a 20% discount: 10.0

Text that isn't a number

int only accepts digits, with a minus sign in front if needed. Anything else stops the program with a ValueError, even a decimal point:

count = int(input("How many? "))
Input
2.5
Output
How many? 2.5
Python stops with
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    count = int(input("How many? "))
ValueError: invalid literal for int() with base 10: '2.5'

The message says that int can't read '2.5' as a whole number ("base 10" just means ordinary digits). If the user may type decimals, read the number with float. A later module shows how a program can deal with input that isn't a number at all.

Your task

Challenge 1 of 3

Fill in the blank so the program reads a whole number and doubles it. If the user types 7, the run looks like this:

Number: 7
7 doubled is 14

Challenge 2

If the user types 3, this program claims that's 3333333 cups a week. When a string is multiplied by a number, Python repeats the string. Fix the program, so that a run looks like this:

Cups of coffee a day: 3
That's 21 cups a week.

Challenge 3

Write a program that asks for the price of an item and the number of items, and prints the total price. The price may have decimals, but the number of items is a whole number. If the user types 2.5 and 4, the run looks like this:

Price: 2.5
Items: 4
Total: 10.0