Python User Input: input() and Validation - Python with AI tutorial chapter 24
Python

Python User Input: input() and Validation

Python with AI Tutorial · Chapter 24 of 48

Python user input is read with the built-in input() function. It pauses the program, shows an optional prompt, waits for the person to type something and press Enter, and returns whatever they typed as a string. Because the result is always text, you must convert and validate it before using it in calculations, usually inside a loop with try...except.

The input() function

Pass the prompt text as the argument. Python prints it, waits, and returns the typed line without the trailing newline. In the examples below the user’s typing is shown after the prompt.

name = input("Customer name: ")
print(f"Welcome, {name}!")
Output:
Customer name: Meera Shah
Welcome, Meera Shah!

End the prompt with a space or colon so the cursor does not sit directly against the text. Keep prompts short and specific: “Quantity (1-99): ” tells the user more than “Enter value: “.

input() always returns a string

Even when the user types digits, the value is text. Adding two inputs joins them instead of summing them, which is one of the most common beginner surprises.

a = input("First amount: ")
b = input("Second amount: ")
print(a + b)
print(type(a))
Output:
First amount: 150
Second amount: 275
150275
<class 'str'>

This behaviour is not a bug. input() cannot know whether “150” is meant to be a number, a product code or a postcode, so it leaves the decision to you. The rule to remember is simple: convert immediately after reading, and keep the raw string only if you need it for an error message.

Converting input to numbers

Wrap the call in int() for whole numbers or float() for decimals. If the text cannot be converted, Python raises a ValueError, which is why the next section adds validation.

qty = int(input("Quantity: "))
unit_price = float(input("Unit price: "))
print(f"Line total: {qty * unit_price:.2f}")
Output:
Quantity: 12
Unit price: 49.99
Line total: 599.88
Function Converts Accepts Fails on
int() Text to whole number "42", " 7 ", "-3" "4.5", "ten", ""
float() Text to decimal "4.5", "1e3", "12" "12,000", "$5"
str.strip() Removes surrounding spaces Any string Never fails
str.lower() Normalises case for yes/no answers Any string Never fails

Validating with try…except

Never trust that the user typed a number. Catch the ValueError and give a helpful message instead of a traceback.

raw = input("Discount percent: ")
try:
    discount = float(raw)
    print(f"Applying {discount:.1f}% discount")
except ValueError:
    print(f"'{raw}' is not a number, no discount applied")
Output:
Discount percent: ten
'ten' is not a number, no discount applied

Asking again until the input is valid

The standard pattern combines while True, try...except and break. The loop keeps asking until a valid value arrives, then exits. Range checks go in the same loop.

while True:
    raw = input("Number of seats (1-8): ")
    try:
        seats = int(raw)
    except ValueError:
        print("Please type a whole number.")
        continue
    if 1 <= seats <= 8:
        break
    print("Seats must be between 1 and 8.")
print(f"Booked {seats} seats")
Output:
Number of seats (1-8): six
Please type a whole number.
Number of seats (1-8): 12
Seats must be between 1 and 8.
Number of seats (1-8): 4
Booked 4 seats
Try it with AI

Ask the assistant to turn the retry pattern into a reusable helper so you never write the loop by hand again.

Write a Python function ask_int(prompt, low, high) that keeps calling input() until the user types a whole number between low and high inclusive, printing a friendly message on each bad attempt, and returns the int. Then write ask_float and ask_yes_no in the same style, and show a short order-entry script that uses all three.

The continue statement sends the loop straight back to the prompt when conversion fails, so the range check below it only ever sees a genuine integer. Separating the two checks like this gives the user a different message for each kind of mistake, which is far more helpful than a single generic warning.

Cleaning text input

People add stray spaces and mixed capitals. Chain .strip() and .lower() before comparing, and compare against a small set of accepted answers.

answer = input("Send invoice by email? (yes/no): ").strip().lower()
if answer in ("y", "yes"):
    print("Emailing invoice")
elif answer in ("n", "no"):
    print("Invoice will be printed")
else:
    print("Answer not recognised")
Output:
Send invoice by email? (yes/no):   YES
Emailing invoice
Common mistake: writing if answer == "yes" or "y":. The string "y" is always truthy, so this condition is always true. Use answer in ("yes", "y") or two full comparisons joined by or.

Reading several values on one line

Ask for comma-separated values and split the string. Each piece still needs converting and stripping. This is handy for quick data entry in a terminal tool.

raw = input("Monthly sales, comma separated: ")
values = [float(v.strip()) for v in raw.split(",") if v.strip()]
print(f"{len(values)} months, total {sum(values):,.0f}, best {max(values):,.0f}")
Output:
Monthly sales, comma separated: 12000, 9800, 15250,11000
4 months, total 48,050, best 15,250

Default values and empty input

If the user presses Enter without typing, input() returns an empty string. Use the or operator to fall back to a default so the script can be run quickly with sensible settings.

currency = input("Currency [INR]: ").strip().upper() or "INR"
year = int(input("Report year [2026]: ") or 2026)
print(currency, year)
Output:
Currency [INR]: 
Report year [2026]: 2025
INR 2025

Showing the default in square brackets is a widely used convention in command-line tools. The user sees what will happen if they just press Enter.

Hiding sensitive input

For passwords or API keys, use getpass.getpass() from the standard library instead of input(). It works the same way but does not echo the typed characters to the screen.

from getpass import getpass

user = input("Username: ")
pin = getpass("PIN: ")
print(f"{user} entered a {len(pin)}-digit PIN")
Output:
Username: pk.finance
PIN: 
pk.finance entered a 4-digit PIN
Try it with AI

Give the assistant a list of fields you need to collect and ask for an interactive data-entry script with validation on every field.

Write an interactive Python script that collects a new employee record from the terminal: full name (not empty), department (must be one of Sales, Finance, Ops), start date in YYYY-MM-DD format, and monthly salary as a positive number. Re-ask on any invalid entry, use strip() and lower() for text, and print the final record as a dictionary. Explain how you validated the date without external libraries.

Terminal input is fine for small internal tools and learning exercises. When a script grows into something colleagues run regularly, consider reading settings from command-line arguments or a configuration file instead, so the same program can be scheduled without anyone typing answers.

Common mistakes

  • Doing arithmetic on the raw string returned by input() without converting it.
  • Converting with int() or float() outside a try block, so one typo crashes the program.
  • Forgetting .strip(), so "yes " with a trailing space is not recognised.
  • Writing == "yes" or "y" instead of in ("yes", "y").
  • Using input() for passwords, which shows them on screen and in terminal history.

Exercise

Write a script that asks for an invoice amount and keeps asking until the user enters a positive number. Then ask whether the customer is a member (yes/no, any capitalisation) and print the payable amount with a 10% discount for members. Use try...except, while True and .strip().lower().

Show answer
while True:
    raw = input("Invoice amount: ")
    try:
        amount = float(raw)
    except ValueError:
        print("Enter a number.")
        continue
    if amount > 0:
        break
    print("Amount must be positive.")

member = input("Member? (yes/no): ").strip().lower() in ("yes", "y")
payable = amount * 0.9 if member else amount
print(f"Payable: {payable:.2f}")
Output:
Invoice amount: abc
Enter a number.
Invoice amount: -50
Amount must be positive.
Invoice amount: 2400
Member? (yes/no): Yes
Payable: 2160.00

Related chapters

FAQ

Why does Python input() return a string?

Everything typed at a keyboard is text, so input() hands it to you unchanged. Convert it explicitly with int() or float() when you need a number, and catch ValueError in case the text is not numeric.

How do I validate user input in Python?

Put the conversion inside a while True loop with try...except ValueError, add any range or membership checks, and break only when the value passes. Re-prompt with a clear message otherwise.

How do I take multiple inputs on one line in Python?

Read one line with input(), then call .split(",") or .split() to break it into pieces and convert each piece. A list comprehension keeps this to a single line.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 24 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com