Python 3 — Reading User Inputs

🐍 Python 3 🟢 Lesson 7 📅 July 2026

Every interactive program needs to accept input from users. Python provides the built-in input() function to pause execution, display a prompt, and wait for the user to type something. This lesson covers reading inputs, converting types, validating data, and building real interactive programs.

1 The input() Function

The input() function displays a prompt to the user, waits for them to type something, and returns their response as a string:

Python 3 — Basic input()▶ Run Code
# Basic input - always returns a string
name = input("What is your name? ")
print(f"Hello, {name}! Welcome to Python.")

# Empty prompt (no message)
value = input()
print(f"You typed: {value}")
2 Converting Input Types

Critical: input() always returns a string, even if the user types a number. You must convert it to the correct type before doing math:

Python 3 — Type Conversion▶ Run Code
# String to Integer
age = int(input("Enter your age: "))
print(f"In 10 years, you will be {age + 10}")

# String to Float
price = float(input("Enter price: "))
tax = price * 0.18
print(f"Price with 18% tax: {price + tax:.2f}")

# Multiple inputs on one line using split()
x, y = input("Enter two numbers (space-separated): ").split()
x, y = int(x), int(y)
print(f"Sum = {x + y}, Product = {x * y}")
3 Reading Multiple Values

Python's split() and map() functions make it easy to read multiple values in one line:

Python 3 — Multiple Inputs▶ Run Code
# Read a list of numbers
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}")
print(f"Average: {sum(numbers) / len(numbers):.2f}")
print(f"Max: {max(numbers)}, Min: {min(numbers)}")

# Read 3 values at once
a, b, c = map(float, input("Enter 3 values: ").split())
print(f"Average of {a}, {b}, {c} = {(a+b+c)/3:.2f}")
4 Input Validation with try-except

Users often type unexpected things. Use try-except to safely handle invalid inputs:

Python 3 — Input Validation▶ Run Code
# Safe integer input with error handling
def get_integer(prompt):
    while True:
        try:
            value = int(input(prompt))
            return value
        except ValueError:
            print("❌ Invalid! Please enter a whole number.")

# age = get_integer("Enter your age: ")
# print(f"Age: {age}")

# Validate range
def get_score():
    while True:
        try:
            score = int(input("Enter score (0-100): "))
            if 0 <= score <= 100:
                return score
            else:
                print("❌ Score must be between 0 and 100!")
        except ValueError:
            print("❌ Please enter a number!")

# score = get_score()
# print(f"Valid score: {score}")
5 Building an Interactive Calculator

Let's build a complete interactive calculator using everything we've learned:

Python 3 — Interactive Calculator▶ Run Code
print("=== Simple Calculator ===")

try:
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))

    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "*":
        result = num1 * num2
    elif operator == "/":
        if num2 == 0:
            print("❌ Cannot divide by zero!")
        else:
            result = num1 / num2
    else:
        print("❌ Unknown operator!")
        result = None

    if result is not None:
        print(f"Result: {num1} {operator} {num2} = {result}")

except ValueError:
    print("❌ Please enter valid numbers!")
6 input() in a Loop

Combine input() with loops to keep asking until the user provides valid data or decides to quit:

Python 3 — Input in Loops▶ Run Code
# Collect items until user types 'done'
shopping_list = []

print("Enter items (type 'done' to finish):")
while True:
    item = input("Add item: ").strip()
    if item.lower() == "done":
        break
    if item:
        shopping_list.append(item)
        print(f"✅ Added: {item}")
    else:
        print("❌ Item cannot be empty!")

print(f"
Your shopping list ({len(shopping_list)} items):")
for i, item in enumerate(shopping_list, 1):
    print(f"  {i}. {item}")
7 Password Input (getpass)

For sensitive inputs like passwords, use getpass.getpass() which hides the typed characters:

Python 3 — getpass▶ Run Code
import getpass

# getpass hides input in terminal (appears blank while typing)
# In Our Compiler, it works like regular input()
username = input("Username: ")
password = getpass.getpass("Password: ")  # Hidden input

correct_user = "admin"
correct_pass = "python123"

if username == correct_user and password == correct_pass:
    print("✅ Login successful! Welcome, Admin.")
else:
    print("❌ Invalid credentials. Access denied.")
⚠️ Common Input Mistakes:
  • Forgetting to convert: int(input(...)) — without int(), math operations will fail or concatenate strings
  • Not handling ValueError when user types text instead of a number
  • Using input() in a loop without a way to exit — always have a break condition
  • Forgetting .strip() to remove leading/trailing whitespace from input
8 Coding Challenge

Build a Number Guessing Game:

  • Set a secret number (e.g., 42)
  • Ask the user to guess in a loop
  • After each guess, tell them if it's "Too high", "Too low", or "Correct!"
  • Count how many attempts it takes
  • Print "Congratulations! You got it in X attempts!"
  • Handle non-numeric inputs gracefully with try-except