Numbers from input()
🌍 In real life. When you type 250 into a calculator app, you press the keys 2, 5 and 0: three characters. The app has to read those characters as a number before it can add anything to them.
Your programs do the same: ask with input(), then read the answer as a number.
The idea in one sentence: int(input(...)) asks a question and turns the answer into a number straight away, because Python works from the inside out.
Its words:
- nesting: putting one call inside another,
int(input("Age: ")) - inside out: Python finishes the inner call first and hands its result to the outer one
Step by step, for age = int(input("Age: ")) when the user types 12:
- The inner call runs first:
input("Age: ")asks, and gives back"12". - The outer call gets that string:
int("12")gives back 12. =puts the number 12 intoage.
age = int(input("Age: "))
print("Next year you will be", age + 1)a = int(input("First number: "))
b = int(input("Second number: "))
print(a, "+", b, "=", a + b)How Python does it. Nesting is only a shortcut. The two-step version does exactly the same thing and can be easier to read: keep the text first, then convert it.
text = input("Number: ")
n = int(text)
print(n * 10)Use float() for answers that might have a decimal point, like prices or heights.
height = float(input("Height in metres: "))
print(height * 100, "cm")If the user types something that isn't a number, int() stops with a ValueError. Chapter 18 shows how to handle errors like this. For now, type carefully!
n = int(input("Number: "))
print(n * 2)Mistakes and edge cases.
- Converting too late.
age = input("Age: ")thenage + 1givesTypeError: can only concatenate str (not "int") to str. Convert as soon as you read it. - A decimal answer for int(). If the user types
12.50,int(...)givesValueError: invalid literal for int() with base 10: '12.50'. Usefloat()for prices. - One bracket short.
int(input("Age: ")givesSyntaxError: '(' was never closed. Two calls need two closing brackets:)). - Spaces around the answer are fine.
int(" 12 ")is 12.
Quiz
In
int(input("Age: ")), what happens first?- input() asks and gets the text
- int() makes a number
- Both happen at the same time
What does this print?
text = "6" n = int(text) print(n * 2)Careful! What does this print?
text = "6" print(text * 2)The user types 2.5 at
int(input()). What happens?- A ValueError: int() can't read a decimal point
- It gives 2
- It gives 3
This should add two numbers. Which line is wrong?
a = int(input("A: ")) b = input("B: ") print(a + b)
Coding tasks
Ask for a number and print double it. If the user types
21, print42.Ask for two whole numbers (one on each line) and print what you get when you multiply them.
Ask for a price (it may have decimals, like
2.5) and then a quantity (a whole number). Print the total cost.