Getting input
Overview
So far, every program has run the same way every time. input() lets a program ask the user a question and use the answer, which makes it interactive — a quiz, a calculator, a game.
Asking a question
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")What is your name? Asha
Nice to meet you, Asha!input():
- prints the prompt (the text in brackets) — note the space at the end, so the answer doesn’t touch the question;
- waits until the user types something and presses Enter;
- returns what they typed, as a string, without the Enter.
input() always returns text
This is the most important thing about input():
Even if the user types 25, you get the string "25". Try to do maths with it and Python complains:
age = input("Age? ")
print(age + 1)TypeError: can only concatenate str (not "int") to strConvert first:
age = int(input("Age? ")) # whole numbers
height = float(input("Height in metres? ")) # decimals
print("Next year you will be", age + 1)Wrapping input() inside int() or float() is a very common pattern.
Cleaning up text input
People type extra spaces, capitals and lower case unpredictably. Tidy the answer before using it:
answer = input("Continue? (yes/no) ").strip().lower()
if answer == "yes": # you'll learn if in the next chapter
print("Continuing…").strip()removes spaces (and tabs and new lines) from both ends..lower()makes comparisons case-insensitive: “YES”, “Yes” and “yes” all become “yes”..title()capitalises each word — useful for names.
Methods can be chained: each returns a new string, and the next method works on that.
Writing good prompts
- Say what to type and in what form:
"Distance in km (e.g. 12.5): "beats"Enter: ". - Give the choices when there are only a few:
"Size (S/M/L): ". - End with a space (or a colon and a space).
When the user types something unexpected
If someone types twelve where you expect a number, int() can’t convert it:
ValueError: invalid literal for int() with base 10: 'twelve'The program stops. For now, that’s fine. In Errors and exceptions you’ll learn to catch the error and ask again, and in While loops to keep asking until the answer is valid.
Testing programs that use input()
You don’t have to type answers by hand every time. You can pipe text into a program from the terminal:
printf "Asha\n12.5\n65\n" | python converter.pyEach line becomes one answer to input(). This trick is how automated tests feed input to programs, and it saves a lot of typing while you’re developing.
Output with print(), again
You’ve used print with commas and f-strings. Two more options are handy with input:
print("Total:", 42, sep=" ") # control the separator
print("Thinking", end="") # stay on the same line
print("...")Remember:
input()gives you a string. Clean it withstrip(), and convert it withint()orfloat()before doing maths.
A friendly unit converter
Ask the user for their name and greet them. Then ask for a distance in kilometres (it may have decimals, like 12.5), convert it to miles (1 km = 0.621371 miles) and print the result rounded to 2 decimal places. Finally ask how many minutes the run took (a whole number) and print the pace in minutes per kilometre, rounded to 1 decimal place. Clean up the name so extra spaces and lower-case letters don’t matter.
# 1. Name and greeting
# 2. Kilometres → miles
# 3. Minutes → pace (minutes per km)# 1. Name and greeting
name = input("What is your name? ").strip().title()
print(f"Hi {name}!")
# 2. Kilometres → miles
km = float(input("Distance in km: "))
miles = km * 0.621371
print(f"{km} km is {round(miles, 2)} miles")
# 3. Minutes → pace (minutes per km)
minutes = int(input("Time in minutes: "))
pace = minutes / km
print(f"Your pace: {round(pace, 1)} min/km")Summary
input("prompt")shows a prompt, waits for the user to press Enter and returns what they typed.input()always returns a string — convert withint()orfloat()before doing arithmetic.- Clean text input with
.strip()and normalise case with.lower()or.title(). - Write clear prompts that say what to type and in what units.
- Converting text that isn’t a number raises ValueError — you’ll learn to handle it in *Errors and exceptions*.