Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Ask Questions in Python With input()

· 4 min read · Home Tech

In this article
  1. Ask a Question and Store the Answer in Python
  2. Match the Conversion to the Answer You Expect
  3. A Worked Example: A Two-Question Script
  4. When the Question Fails to Appear or the Answer Is Wrong
  5. Where input() Fits and Where It Does Not

Use the built-in input() function: name = input("What is your name? ") shows the question on screen, waits for the user to type, and stores what they typed as a string. Convert the answer with int() or float() when you need a number.

Time 5 min · Steps 7 · Level Easy

Ask a Question and Store the Answer in Python

  1. Write the question inside input(). Type answer = input("What is your name? ") in your script or the Python shell. The text in quotes appears on screen, followed by a blinking cursor.
  2. Run the file. Save the script as a .py file and run it (in most editors, the Run button or Run menu). The question prints and the program pauses until you press Enter.
  3. Type a reply and press Enter. Whatever you typed is now stored in the variable on the left of the equals sign, as text.
  4. Print the answer back. Add print("Hello, " + answer) on the next line to confirm the program received it.
  5. Convert numbers with int() or float(). age = int(input("How old are you? ")) turns the typed text into a whole number; use float() for decimals like 4.5.
  6. Handle bad input with try and except. Wrap the conversion in try: ... except ValueError: print("Please type a whole number.") so the program does not crash when someone types letters.
  7. Loop until the answer is valid. Put the question inside a while loop and only break out once the conversion succeeds, so the user gets asked again instead of ending the program.

Match the Conversion to the Answer You Expect

input() always gives you a string, even if the user types 42. Choose the conversion before you write the line, based on what the answer will be used for.

If the answer is...Then convert with...Example
A name or any textNothing - keep the stringcity = input("City? ")
A whole number (age, count)int()age = int(input("Age? "))
A decimal (height, price)float()height = float(input("Height in metres? "))
Yes or noCompare the string, lowercasedif input("Continue? ").lower() == "y":

One detail worth knowing: input() strips the newline when Enter is pressed, so you do not need to remove it yourself. Extra spaces the user types at the end, however, stay in the string - strip() removes them if that matters.

A Worked Example: A Two-Question Script

Here is a complete script that asks for a name and a number, then uses both. Type it into a new file and run it.

name = input("What is your name? ")

while True:
    try:
        age = int(input("How old are you? "))
        break
    except ValueError:
        print("Please type a whole number, like 25.")

print("Hello, " + name + ".")
print("Next year you will be", age + 1)

Run it once with sensible answers: type Amina, press Enter, type 25, press Enter. The output reads Hello, Amina. and Next year you will be 26. Run it again and type twenty-five at the age question: the loop prints the error message and asks again instead of crashing - that is the try/except doing its job.

When the Question Fails to Appear or the Answer Is Wrong

Most problems with input() come from one of four causes, and each has a direct fix.

SymptomCauseFix
TypeError: can only concatenate str to strYou added a number to the answer stringConvert with int() or float(), or build the message with a comma in print()
ValueError: invalid literal for int()Letters typed where a number was expectedWrap the conversion in try/except, as in the worked example
Question never shows on screenScript not run, or input() result not assignedRun the file rather than only saving it; check the equals sign
Answer seems emptyUser pressed Enter without typingCheck with if answer == "": and ask again

Another common surprise: comparing "25" to 25 returns False, because one is text and one is a number. Convert first, then compare.

Where input() Fits and Where It Does Not

input() is the right tool for small scripts, exercises, command-line tools and anything you run yourself. It is not the tool for a web page - a browser cannot reach your Python console - and it is awkward for programs that must run without a person at the keyboard.

  • If the script runs in a terminal with a person answering, use input().
  • If the same question is asked many times with fixed options, ask for a single letter or number and compare it, so "1" is easier to type than a full word.
  • If the program runs unattended (a scheduled job), read values from a file or command-line arguments instead of asking.
  • If you are writing a graphical app or a web backend, use that framework's own form or dialog tools; input() will not appear anywhere the user can see.

For anything beyond simple scripts, the argparse module handles questions passed to the program when it starts, and it is part of Python's standard library.

One habit worth forming early: put the question text inside input() rather than printing it separately. print("Name?") followed by input() works, but the cursor then sits on the next line, which looks odd to whoever is answering.

Official source: Python Software Foundation