Command Palette

Search for a command to run...

Hectal
PHASE 1Beginner ~26 min· topic 10 of 11

Topic 1.10

Reading Input with input()

In one line

input(prompt) pauses the program, shows the prompt, waits for the user to type a line and press Enter, and returns what they typed as a string. Convert it with int() or float() before calculating, and check it before you trust it. input() does not work in the browser panels on this site, so the examples here use fixed values.

Think of it like this

A form with a blank line. A clerk hands you a form: "Name: ______". Nothing happens until you write something and hand it back. input("Name: ") is that blank line: the program stops, shows the question, and waits for the person to type.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

input()
A function that waits for the user to type a line and returns it as a string.
Prompt
The message shown before the program waits for typing.
Standard input
The stream a program reads typed text from, usually the keyboard.
Validate
Check that input is acceptable before you use it.
strip()
A string method that removes spaces from both ends.
isdigit()
A string method that is True when the text is non-empty and made only of digits.
Command-line argument
A word typed after the program name, available in sys.argv.
sys.argv
The list of command-line arguments as strings. Item 0 is the program name.

Step by step

01The program waits

When Python reaches input("What is your name? ") it prints the prompt and then stops. It resumes only when the person presses Enter. The text they typed becomes the value of the call. In a terminal the session looks like this.

greet.pywhole filepython
name = input("What is your name? ")
print("Hello,", name)
age_text = input("How old are you? ")
age = int(age_text)
print("Next year you will be", age + 1)
terminal
$ python greet.py
── expected output ──
What is your name? Asha
Hello, Asha
How old are you? 12
Next year you will be 13

02Everything arrives as text

age_text is the string "12". age_text + age_text joins to "1212", and age_text + 1 is a TypeError. After int(age_text) it is the number 12 and the maths works. It is good practice to name the raw text clearly (age_text) and the converted number plainly (age).

Everything arrives as textdiagram
Rendering diagram…

03Clean the text

" Asha ".strip() gives "Asha". .title() capitalises each word. .isdigit() asks whether the text is all digits. These are string methods, functions that belong to a string and are called with a dot (Topic 3.2 covers many more).

main.pywhole filepython
raw = "  asha  "
clean = raw.strip().title()
print(repr(raw), repr(clean))     # '  asha  ' 'Asha'
print("12".isdigit(), "12a".isdigit(), "".isdigit())    # True False False

04Check before you convert

The program below uses if and else (you will learn them in Topic 2.1): *if* the text is all digits, do the first block, *else* do the second. It never crashes on bad text. For now, read it as plain English.

age.pywhole filepython
age_text = input("How old are you? ")
if age_text.isdigit():
    print("Next year you will be", int(age_text) + 1)
else:
    print("Please type digits only.")
terminal
$ python age.py
── expected output ──
How old are you? abc
Please type digits only.

05What happens without the check

If the first program gets abc for the age, int("abc") raises ValueError, and the traceback points at the int line. The error message includes the bad text, which is useful for you but not for the user. Real programs catch it and ask again (Topic 7.1).

terminal
$ python greet.py
── expected output ──
What is your name? Asha
How old are you? abc
Traceback (most recent call last):
File "greet.py", line 4, in <module>
age = int(age_text)
^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'

06Command-line arguments (a preview)

Instead of asking while the program runs, you can give values when you start it. sys.argv is a list of strings. Index 0 is the program's own name. If you did not give an argument, sys.argv[1] is an IndexError.

For anything beyond one or two values, use the argparse module, which gives help text, defaults and type conversion for free. Topic 15.7 covers it.

hello.pywhole filepython
import sys

print(sys.argv)
print("Hello,", sys.argv[1])
terminal
$ python hello.py Asha
── expected output ──
['hello.py', 'Asha']
Hello, Asha

Try it yourself

  1. 1

    Change the typed value

    In the first example, change age_text to "40", then to "abc". The second one stops with a ValueError: that is what a user typing letters causes.

  2. 2

    Run it on your computer

    Save the greet.py program, open a terminal in that folder, and run python greet.py (or python3/py, Topic 0.4). Try typing a name with extra spaces, then add .strip() to clean it.

  3. 3

    Add two typed numbers

    Write a program that asks for two numbers with input, converts them with float, and prints their sum. Test with 2.5 and 4.

Code & diagrams

Typed text stands in for input() New tab

On your own computer, replace the first line with typed = input("Name: "). Everything else is the same.

Sign in to run this example in your browser.

Expected output

Hello, Asha
Next year you will be 13
1212
'  Asha  ' 'Asha'
[Asha]
True False False
Text in, numbers out New tab

typed_a and typed_b are what a person would type. Notice that + joins text but adds numbers.

Sign in to run this example in your browser.

Expected output

75
12
5.0
KM
A real input() programpython

Not runnable here: the browser has no keyboard stream. Save it as greet.py and run it in a terminal.

name = input("What is your name? ")
print("Hello,", name)
age_text = input("How old are you? ")
age = int(age_text)
print("Next year you will be", age + 1)

Output

What is your name? Asha
Hello, Asha
How old are you? 12
Next year you will be 13

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Calculate with the raw text

Add 1 to the text returned by input() without converting it.

main.pywhole filepython
age_text = "12"
print(age_text + 1)
terminal
$ python main.py
── what you'll see ──
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(age_text + 1)
~~~~~~~~~^~~
TypeError: can only concatenate str (not "int") to str

Break #2

Type letters where a number is needed

Type abc when the program asks for an age.

greet.pywhole filepython
age = int(input("How old are you? "))
terminal
$ python greet.py
── what you'll see ──
How old are you? abc
Traceback (most recent call last):
File "greet.py", line 1, in <module>
age = int(input("How old are you? "))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'

Myth vs fact

Myth

input() returns a number if the user types digits.

Fact

It always returns a string. input() followed by + 1 is a TypeError; you must convert.

Myth

If the user types a number, the program can trust it.

Fact

Users (and files, and web requests) send anything. Programs check input at the edge before using it.

Myth

input() is how all programs get data.

Fact

It is the simplest way. Real programs also read command-line arguments, files, environment variables, network requests and databases, all of which arrive as text or bytes first.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    input() reads from sys.stdin. When you pipe or redirect (echo Asha | python greet.py), the same code reads from the pipe, which is how programs are tested without a keyboard. It raises EOFError if the input ends before a line arrives.

  • ▸

    For secret input such as passwords use getpass.getpass(), which does not echo the typed characters. Never print or log secrets.

  • ▸

    str.isdigit() is a weaker check than it looks: it is True for characters such as superscript "²", which int() then rejects with ValueError. str.isdecimal() matches what int() accepts, but a leading - or + still fails both tests, so "-5".isdigit() is False even though int("-5") works. The reliable test is to try the conversion and catch ValueError (Topic 7.1): it is the Python idiom of "easier to ask forgiveness than permission" (EAFP).

  • ▸

    For competitive programming and large inputs, input() is slow. Read everything at once with sys.stdin.read() or per line with sys.stdin.readline, which keeps the trailing newline. input() also strips that newline and raises EOFError at end of input, whereas readline() returns "". If the readline module has been imported, input() gains line editing and history in a terminal.

  • ▸

    Web apps, APIs and AI tools receive their input as JSON or form text. Pydantic (Phase 15) validates and converts that input from type hints, which is the modern version of the .strip(), .isdigit() and int() steps in this topic.

  • ▸

    When asking an LLM for structured answers, the model's reply is also untrusted text: parse and validate it exactly as you would typed input.

Remember this

  1. 1

    input() always returns a string, even when the person types digits. If they type 12, you get the text "12", not the number 12. Joining it as text works ("12" + "12" is "1212"), but arithmetic does not. You must convert: age = int(input("Age: ")). This is the single most common beginner surprise with input.

  2. 2

    The text you pass in, the prompt, is shown without a new line, so end it with a space: input("Name: "). What the person types is returned without the final Enter. print shows output; input is how a program receives input.

  3. 3

    People type surprising things: extra spaces, capital letters, letters instead of digits, nothing at all. Never trust input. Clean it with .strip() (removes spaces from both ends) and .title() or .lower(). These are string methods: functions that belong to a piece of text and are called with a dot. Check it before converting: text.isdigit() is True only when the text is all digits. If you convert bad text, int("abc") raises a ValueError and the program stops.

  4. 4

    To check input you need if, which Phase 2 teaches. To retry until it is valid you need a loop (Phase 2), and to recover instead of stopping you need try/except (Topic 7.1). Until then, this topic shows the pattern in non-runnable blocks, so you can read it now and use it fully later.

  5. 5

    input() works in a terminal (python greet.py) and in the interactive shell. It does not work in the in-page Run button on this site, because the browser runs your program without a keyboard stream. For the runnable examples we put the "typed" text into a variable, such as typed = "Asha", and the rest of the code is identical. On your computer, replace that line with input().

  6. 6

    A second way to pass information into a program is on the command line: python greet.py Asha makes the list sys.argv equal to ['greet.py', 'Asha']. The first item is the program name and the rest are always strings. Serious tools use the argparse module for this (Topic 15.7). Input also arrives from files, from the network and from environment variables (settings that the operating system hands to a program). All of it is text first.

Explain it without notes

01

What type does input() return? Why does input("Age: ") + 1 fail?

02

How do you read a whole number from the user, and what can go wrong?

03

Why do the examples in this course use fixed values instead of input() in the Run button?

04

What is sys.argv?

Practice

01

Write a program that asks for a name and prints Hello, <name>!. Then write the same program with a fixed value in place of input() so it can run here.

02

Given the text typed = " 42 ", print the number plus 8.

03

Given the texts a = "3.5" and b = "1.5", print their sum as a number.

Trade-offs

  • ↔

    Prompting vs. command-line arguments. Prompts are friendly for a person at a keyboard, but cannot be scripted. Arguments and files are easy to automate but need to be remembered or documented.

  • ↔

    Validate early vs. fail fast. Checking input and showing a polite message is kinder to the user. Letting the program crash with a ValueError is acceptable for a quick personal script, but not for software others will use.

Done when you can

  • Done when you can explain that input() returns a string.

  • Done when you can read a number from the user with int(input(...)) or float(input(...)).

  • Done when you can clean text with .strip() and check it with .isdigit().

  • Done when you can say why input examples here use fixed values and how to switch to real input().

  • Done when you can print sys.argv for a program run with an argument.