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.
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)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).
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).
raw = " asha "
clean = raw.strip().title()
print(repr(raw), repr(clean)) # ' asha ' 'Asha'
print("12".isdigit(), "12a".isdigit(), "".isdigit()) # True False False04Check 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_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.")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).
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.
import sys
print(sys.argv)
print("Hello,", sys.argv[1])Try it yourself
- 1
Change the typed value
In the first example, change
age_textto"40", then to"abc". The second one stops with aValueError: that is what a user typing letters causes. - 2
Run it on your computer
Save the
greet.pyprogram, open a terminal in that folder, and runpython greet.py(orpython3/py, Topic 0.4). Try typing a name with extra spaces, then add.strip()to clean it. - 3
Add two typed numbers
Write a program that asks for two numbers with
input, converts them withfloat, and prints their sum. Test with2.5and4.
Code & diagrams
On your own computer, replace the first line with typed = input("Name: "). Everything else is the same.
Expected output
Hello, Asha
Next year you will be 13
1212
' Asha ' 'Asha'
[Asha]
True False Falsetyped_a and typed_b are what a person would type. Notice that + joins text but adds numbers.
Expected output
75
12
5.0
KMNot 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 13Break 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.
age_text = "12"
print(age_text + 1)Break #2
Type letters where a number is needed
Type abc when the program asks for an age.
age = int(input("How old are you? "))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 fromsys.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 raisesEOFErrorif 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 isTruefor characters such as superscript"²", whichint()then rejects withValueError.str.isdecimal()matches whatint()accepts, but a leading-or+still fails both tests, so"-5".isdigit()isFalseeven thoughint("-5")works. The reliable test is to try the conversion and catchValueError(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 withsys.stdin.read()or per line withsys.stdin.readline, which keeps the trailing newline.input()also strips that newline and raisesEOFErrorat end of input, whereasreadline()returns"". If thereadlinemodule 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()andint()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
input()always returns a string, even when the person types digits. If they type12, 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
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.printshows output;inputis how a program receives input. - 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 aValueErrorand the program stops. - 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 needtry/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
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 astyped = "Asha", and the rest of the code is identical. On your computer, replace that line withinput(). - 6
A second way to pass information into a program is on the command line:
python greet.py Ashamakes the listsys.argvequal to['greet.py', 'Asha']. The first item is the program name and the rest are always strings. Serious tools use theargparsemodule 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
What type does input() return? Why does input("Age: ") + 1 fail?
How do you read a whole number from the user, and what can go wrong?
Why do the examples in this course use fixed values instead of input() in the Run button?
What is sys.argv?
Practice
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.
Given the text typed = " 42 ", print the number plus 8.
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
ValueErroris 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(...))orfloat(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.argvfor a program run with an argument.