Python - User Input

Overview

Estimated time: 10–20 minutes

Read input from users via the console and validate it safely.

Learning Objectives

  • Use input() to read strings from stdin.
  • Parse numbers with int()/float() and handle exceptions.
  • Prompt clearly and loop until valid input is received.

Prerequisites

Reading input

name = input("Your name: ")
print(f"Hello, {name}!")

Validation with try/except

while True:
    raw = input("Enter an integer: ")
    try:
        n = int(raw)
        break
    except ValueError:
        print("Invalid integer, try again.")
print(n)

Common Pitfalls

  • Assuming input is always valid; always handle ValueError.
  • Forgetting to strip whitespace: use .strip().

Checks for Understanding

  1. What does input() return?
  2. How do you handle non-integer input when parsing?
Show answers
  1. A string.
  2. Wrap int(raw) in a try/except ValueError.

Exercises

  1. Prompt for a float and print its square rounded to 2 decimals.
  2. Read a comma-separated list of numbers and print their sum.