15. Getting input
So far you have written every value yourself: predictable, but not
interactive. This chapter introduces input(), which waits
for the user to type into the terminal.
input() — read one line
input(prompt) prints an optional prompt, then waits for
the user to type a line and press Enter. It returns
whatever was typed as a string, without the
newline.
name = input("What is your name? ")
print("Hello, " + name)Run it. It prints the question on the same line as the cursor, waits for your name and Enter, prints the greeting, then exits.
Open exercises/15/01-read-name.py and run it twice with
different names. Watch the greeting change to match.
The prompt is on the same line
Python's input() puts the prompt and the user's cursor
on the same line automatically. You do not need a separate function for
this. The text you pass to input() is the prompt:
name = input("What is your name? ")
print(f"Hello, {name}")Output:
What is your name? Keiko
Hello, Keiko
Reading a number
input() always returns a string, even
for digits. To do maths, wrap it in int() for a whole
number or float() for a decimal:
text = input("Enter a number: ")
n = int(text)
print(f"Twice that is {n * 2}")The two steps (read, then convert) can be written on one line:
n = int(input("Enter a number: "))
print(f"Twice that is {n * 2}")The inner call runs first and returns the string; the outer turns it into an integer.
If the user types something that is not a number, int()
raises a ValueError and the program crashes. You will fix
this in a later chapter using try/except. For
now, just type numbers when the program asks for them.
Reading several values
To read several values, call input() once per value:
a = int(input("First number: "))
b = int(input("Second number: "))
print(f"Sum: {a + b}")Each call pauses and waits separately. The program does not continue to the next line until Enter is pressed.
Homework
Problem 1 — Greet by name
Open exercises/15/homework/01-greet-by-name.py. Prompt
for a first name with input(), read it, then print
Hello, <name>!. The exclamation mark is part of the
output.
Problem 2 — Sum of two
Open exercises/15/homework/02-sum-of-two.py. Prompt for
two numbers (separate prompts), convert each with int(),
then print the sum like this:
a + b = c
where a, b, c are the actual
values.
Problem 3 — Years to retirement
Open exercises/15/homework/03-retirement.py. Ask the
user's age and compute the years left until 65. Print:
You have N years until retirement.
(If someone is over 65, the number is negative. That is fine — no need to handle that case yet.)
Challenge — BMI
Open exercises/15/homework/04-bmi.py. Ask for height in
metres (a decimal like 1.78) and weight in kilograms (like
72.5). Use float() to convert both. Compute
Body Mass Index:
bmi = weight / (height * height)
Print the result rounded to one decimal place using an f-string with
:.1f. Label it clearly.
Stuck or finished? Open the homework solutions page.