Python User Input
Tutorial 32 of 65 · pythondeck.com Python course
input() reads a line of text from stdin and returns a string. Convert to other types yourself. Use argparse for command-line arguments and getpass for hidden password input.
Interactive programs read from stdin with input(), which always returns a string. Validation and conversion (int(), float()) are your responsibility—never trust raw input for security-sensitive operations. Command-line tools scale better with argparse than with manual sys.argv parsing.
Passwords and secrets should use getpass to suppress echo. For richer prompts (choices, paths), consider questionary or similar libraries, but the stdlib covers most scripting needs.
input(prompt) and explicit conversion with error handling.
argparse: positional args, options, types, defaults, subcommands.
getpass.getpass for passwords; never log secret values.
Environment variables via os.environ for twelve-factor style config.
sys.argv basics and why argparse is preferred.
EOF on piped stdin: EOFError when input ends unexpectedly.
Validate ranges and formats after reading strings—reprompt in tutorials, exit with code 1 in CLI tools. argparse supports type=, choices=, and custom types that raise ArgumentTypeError.
Separate "user interface" (prompts, messages) from "business logic" (functions that take plain parameters) so you can test logic without simulating stdin.
For non-interactive automation, read from files or env vars instead of input(); design CLIs to accept --flag values for scripting.
Calling int(input()) without try/except for invalid numbers.
Assuming input is sanitised for SQL, shell, or path operations.
Echoing passwords in logs or debug prints.
Hard-coding prompts only in English without considering encoding on Windows consoles.
Ignoring exit codes: CLI should use sys.exit with non-zero on failure.
Wrap conversions in clear error messages; use argparse for anything beyond toy scripts.
Use getpass for secrets; load config from env vars in production.
Provide --help and sensible defaults; document examples in README.
Test CLI modules by calling main(argv) with fake argument lists.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates prompt. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Prompt
# Run in the REPL or save as a .py file and execute with python.
name = input("Your name? ")
age = int(input("Your age? "))
print(f"Hello {name}, in 10 years you will be {age + 10}.")
This sample walks through argparse in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: argparse
# Run in the REPL or save as a .py file and execute with python.
import argparse
p = argparse.ArgumentParser()
p.add_argument("--name", default="world")
p.add_argument("-n", type=int, default=1)
args = p.parse_args(["--name", "ada", "-n", "3"])
for _ in range(args.n):
print("hello", args.name)
Here is a hands-on illustration of getpass. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: getpass
# Run in the REPL or save as a .py file and execute with python.
from getpass import getpass
pw = getpass("password: ")
print("len:", len(pw))
The program below demonstrates input validation. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# input() returns str — validate before converting
def ask_age(): # loop until valid
while True: # retry loop
raw = input("Age: ").strip() # read and trim (demo: set raw='25')
if raw.isdigit(): # simple numeric check
return int(raw) # success
print("Please enter digits only.") # friendly error
age = ask_age() # in REPL, predefine raw via editing for tests
print("next year:", age + 1) # arithmetic after validation
name = input("Name: ").strip().title() # normalize casing
print(f"Hello, {name}") # greeting
This sample walks through menu loop in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Classic text menu driven by user choice
def menu(): # display options
print("1) Sum 2) Quit") # options
return input("Choice: ").strip() # read selection
running = True # control flag
while running: # until user quits
choice = menu() # show + read
if choice == "1": # sum branch
a = float(input("A: ") or 0) # default 0 if blank
b = float(input("B: ") or 0) # second operand
print(a + b) # result
elif choice == "2": # quit branch
running = False # exit loop
else: # unknown
print("Unknown option") # reprompt next iteration