How to Ask for Input in Python: input(), Types, and Loops
In this article
Use the built-in input() function: name = input("What is your name? ") pauses the program, shows the prompt, and returns whatever the user types as a string. Convert the result with int() or float() when you need a number.
Time 2 min · Steps 5 · Level Easy
When input() Is the Right Tool
Use input() for any script that runs in a terminal, command prompt, or interactive shell and needs a quick answer from the person running it. It is the standard way to collect names, menu choices, numbers, and yes/no answers in beginner scripts, homework exercises, small utilities, and prototypes. It is not the right tool for programs with a graphical interface (use a GUI toolkit's dialog or field instead) or for web apps (use a form field). input() always returns a string, even if the user types digits, so the conversion step below is where most scripts either work or break.
Before You Ask the User Anything
Check these three things first so the steps run cleanly:
- Python 3 installed and running: type
python --versionin a terminal;input()behaves the same across Python 3 versions, but Python 2'sraw_input()is a different function you should not use. - A prompt string planned out: the text inside the parentheses, such as
"Enter your age: ". A clear prompt prevents the user staring at a blinking cursor with no idea what to type. - A decision on the type you need: string, integer, or decimal. Write it down before coding, because it decides whether you wrap the call in
int()orfloat().
Asking for Input in Python: The Steps
- Write the call with a prompt. Type
answer = input("Enter your name: ")in a script or the shell. The text in quotes appears on screen exactly as written, and the trailing space keeps the user's typing off your question mark. - Run the script and type a response. Save the file (for example
greet.py), run it withpython greet.py, type your answer, and press Enter. The program resumes only after Enter is pressed. - Convert to a number when you need one. Wrap the call:
age = int(input("Enter your age: "))for whole numbers, orprice = float(input("Enter a price: "))for decimals. Arithmetic likeage + 1fails on a raw string. - Handle bad input with try/except. Put the conversion in a
try:block and catchValueErrorin anexcept:block that prints a friendly message, so typing "twelve" instead of 12 does not crash the script. - Repeat until the input is valid. Wrap steps 3 and 4 in a
while True:loop and usebreakonce the conversion succeeds. This is the standard pattern for a question the user must answer correctly before the program continues.
A Worked Example: A Number-Guessing Prompt
Here is a complete script that asks for a number and keeps asking until it gets one:
while True:
try:
guess = int(input("Guess a number 1-10: "))
break
except ValueError:
print("That is not a whole number. Try again.")
if guess == 7:
print("Correct!")
else:
print("Not it. You typed", guess)Run it and type 7: it prints Correct! and exits. Run it again and type dog: it prints the error message and asks again, because int("dog") raises ValueError, which the except block catches. Type 3.5 and it also asks again, since int() rejects decimals with a fractional part. The loop runs as many times as the user mistypes, and guess is guaranteed to hold an integer by the time break runs.
Why Your Script Crashes After input()
Most failures come from one of four specific mistakes, and each has a recognizable signature:
- Doing math on a string.
age = input("Age: ")thenage + 1raisesTypeError: can only concatenate str (not "int") to str, because the value is text. Fix it withint(age)at the point of use, or wrap the input call. - Forgetting the parentheses or the variable. Typing
input "Age: "is a syntax error, and callinginput()without saving the result means the answer is discarded the moment the next line runs. - Comparing a string to a number.
if input("Number: ") == 5:is never true, because"5"and5are different values. Convert first, then compare. - Leaving a stray prompt in loops. Putting
input()inside a loop that should only print re-asks the user on every pass. Move the call above the loop when the answer is needed once.
Reading Several Answers in a Row
When a script needs multiple pieces of information, ask for them one at a time with a separate prompt for each, rather than one prompt the user must parse. For example:
first = input("First name: ")
last = input("Last name: ")
print("Hello,", first, last)For a fixed number of numeric answers, a for loop with range(3) collects three values into a list:
scores = []
for i in range(3):
scores.append(int(input(f"Score {i + 1}: ")))
print("Total:", sum(scores))The f"Score {i + 1}: " prompt numbers the questions so the user knows how many are left. Entering 3, 4, and 5 prints Total: 12.
How to Check That the Input Worked
Print the value and its type right after collecting it: print(answer, type(answer)). If you see <class 'str'> where you expected <class 'int'>, the conversion is missing. Test the script three times: once with the expected answer, once with an empty Enter press (which returns an empty string ""), and once with nonsense like abc where a number is required. A script that survives all three runs is ready to hand to someone else.
Does input() Work in Notebooks and IDEs?
Yes, with a visual difference. In Jupyter notebooks and most IDEs' built-in consoles, the prompt appears inline or in a small input box rather than a terminal window, and the program waits exactly as it does in a terminal. In some IDEs you may need to click into the console pane before typing. One environment where input() does not work is a scheduled or background task with no user attached: with no one at the keyboard, the call blocks forever, so remove interactive prompts from any script you run automatically.
Official source: Python Software Foundation