Chapters
Python114 chapters

BasicsChapter 14 of 114

User Input

Read something the person running your program typed, and convert it safely.

input() reads a line

input() stops the program, waits for a line to be typed, and hands it back as a string. The argument is the prompt shown first:

Python
name = input("What is your name? ")
print(f"Hello, {name}")

On this page the Run button will ask you for the values first, because the page has to collect them before the program starts. In a terminal it simply waits.

What you get back is always text

This is the single most common beginner bug. Even when the person types digits, you get a string:

Python
typed = "25"
print(type(typed))
print(typed + 10 if False else "adding a number to it would fail")

Output

<class 'str'>
adding a number to it would fail

Convert it before doing arithmetic:

Python
typed = "25"
age = int(typed)
print(age + 10)

Output

35

Guarding against nonsense

int() raises ValueError on anything that is not a whole number, so real programs check. Here is the shape, with the typing simulated so it runs:

Python
def parse_age(text):
    try:
        return int(text)
    except ValueError:
        return None

for typed in ["30", "thirty", "-4"]:
    age = parse_age(typed)
    if age is None:
        print(typed, "-> not a number")
    elif age < 0:
        print(typed, "-> ages are not negative")
    else:
        print(typed, "-> ok,", age)

Output

30 -> ok, 30
thirty -> not a number
-4 -> ages are not negative

Note the is None test rather than if not age: a perfectly good age of 0 would be falsy and get rejected by the sloppier version.

Asking until it works

In a terminal program the usual pattern is a loop that only ends on good input:

Python
while True:
    text = input("Age: ")
    try:
        age = int(text)
    except ValueError:
        print("Please type a whole number.")
        continue
    if age < 0:
        print("That cannot be negative.")
        continue
    break

print("Thanks, you are", age)

Tidy up what you get

People add spaces and inconsistent capitals. strip() and lower() cost nothing and remove a whole class of bug:

Python
answer = "  Yes \n"
cleaned = answer.strip().lower()
print(repr(answer))
print(repr(cleaned))
print(cleaned in ("y", "yes"))

Output

'  Yes \n'
'yes'
True

Several values on one line

Split the line and unpack it:

Python
line = "3 4"
x, y = line.split()
print(int(x) + int(y))

Output

7

split() with no argument breaks on any run of whitespace and ignores extras at the ends, which is almost always what you want for typed input.

Test yourself

2 questions

What type does input() return?

Show the answer

str, always — It is always a string. Forgetting to convert is the single most common beginner bug.

Why test 'if age is None' rather than 'if not age' after parsing?

Show the answer

Because 0 is a valid value and would be falsy — Truthiness and absence are different questions. An age of 0 is real data; failure to parse is not.

Next chapter

Strings

Text in Python, the quotes you can use, and the fact that strings never change.