Getting input

Topic 4 of 5 in Values and variables5 min readBeginnerFree course

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

Python
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")
Text
What is your name? Asha
Nice to meet you, Asha!

input():

  1. prints the prompt (the text in brackets) — note the space at the end, so the answer doesn’t touch the question;
  2. waits until the user types something and presses Enter;
  3. returns what they typed, as a string, without the Enter.

input() always returns text

This is the most important thing about input():

input() always gives you text. The user types 25 on the keyboard; input(“Age? “) returns ‘25’ as a str; int(…) converts it; and the result is 25, an int. Code: age = int(input(“Age? “)); print(“Next year you will be”, age + 1). Typing “twenty” raises ValueError: invalid literal for int() with base 10.

Even if the user types 25, you get the string "25". Try to do maths with it and Python complains:

Python
age = input("Age? ")
print(age + 1)
Text
TypeError: can only concatenate str (not "int") to str

Convert first:

Python
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:

Python
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:

Text
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:

Terminal
printf "Asha\n12.5\n65\n" | python converter.py

Each 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:

Python
print("Total:", 42, sep=" ")       # control the separator
print("Thinking", end="")          # stay on the same line
print("...")

Remember: input() gives you a string. Clean it with strip(), and convert it with int() or float() before doing maths.

Exercise

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.

Python
# 1. Name and greeting

# 2. Kilometres → miles

# 3. Minutes → pace (minutes per 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 with int() or float() 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*.