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)
8Guests: 8Traceback (most recent call last):
File "main.py", line 2, in <module>
print(guests + 2)
~~~~~~~^~~
TypeError: can only concatenate str (not "int") to strThe 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.")
8Guests: 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.")
3Dog'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}")
12.5Price: 12.5
With a 20% discount: 10.0Text 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? "))
2.5How many? 2.5Traceback (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.