🌱 Phase 1 · Foundations 🟢 Beginner MODULE 05

Input & Output

⏱️ 30 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Phase 183%
🎯 What you'll learn: The full power of print() — its sep, end, and formatting parameters. How input() works and why its result is always a string. How to cast user input to numbers, collect multiple inputs in one line, validate input, and build complete interactive console programs.

print() — In Depth

You've used print() since Lesson 1, but it has several powerful parameters that most beginners never discover. Understanding them makes your output cleaner and more professional.

ParameterDefaultPurpose
*objectsOne or more values to print, separated by commas
sep" " (space)String placed between multiple values
end"\n" (newline)String printed after the last value
filesys.stdoutWhere to write output (advanced — file objects)
flushFalseForce immediate output (advanced — buffering)
print_params.py
PYTHON
# Default print — sep=" ", end="\n"
print("Python", "is", "great")        # Python is great

# Custom sep — change the separator
print("Python", "is", "great", sep="-")  # Python-is-great
print("2025", "01", "15", sep="/")       # 2025/01/15
print(1, 2, 3, 4, 5, sep=", ")          # 1, 2, 3, 4, 5
print("a", "b", "c", sep="")             # abc (no separator)

# Custom end — don't move to next line
print("Loading", end="...")
print("Done!")                            # Loading...Done!

# Build a line without loops
for i in range(5):
    print(i, end=" ")                      # 0 1 2 3 4
print()  # blank print() to move to next line

# Print nothing — just a blank line
print()
print("After the gap")

Number Formatting in print()

number_formatting.py
PYTHON
pi       = 3.14159265
price    = 1999999.5
percent  = 0.875

# Decimal places with f-strings
print(f"Pi (2dp): {pi:.2f}")            # Pi (2dp): 3.14
print(f"Pi (5dp): {pi:.5f}")            # Pi (5dp): 3.14159

# Thousands separator
print(f"Price: {price:,.2f}")            # Price: 1,999,999.50

# Percentage
print(f"Score: {percent:.1%}")           # Score: 87.5%

# Width padding (right-align numbers in columns)
print(f"{'Name':10} {'Score':>6}")
print(f"{'Ali':10} {95:>6}")
print(f"{'Muhammad':10} {88:>6}")
# Name        Score
# Ali            95
# Muhammad       88

input() — Getting User Data

The input() function pauses your program, displays a prompt, and waits for the user to type something and press Enter. It always returns a string — no matter what the user typed.

1
Program reaches input()
Python displays the prompt text you provide and pauses execution — the program freezes, waiting.
2
User types and presses Enter
Everything the user typed (before Enter) is captured as a single string. The Enter key itself is NOT included.
3
input() returns the string
The return value is assigned to your variable. Program continues. Always a str — even if the user typed 42.
Terminal — input() in action
$ python3 greet.py
Enter your name: Sara ← user types this
Enter your age: 21 ← user types this
Hello Sara! You were born in 2004.
input_basics.py
PYTHON
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# CRITICAL: input() ALWAYS returns a string!
raw_age = input("Enter your age: ")
print(type(raw_age))         # <class 'str'> — even if user typed 21

# Convert to int to do arithmetic
age = int(raw_age)
birth_year = 2025 - age
print(f"You were born in {birth_year}.")

# One-liner: convert immediately on input
age = int(input("Enter your age: "))      # concise
price = float(input("Enter price (PKR): ")) # for decimals
⚠️
The #1 beginner mistake with input()
Forgetting that input() returns a string. If a user types 5 and you try to add 3 without converting, Python gives: TypeError: can only concatenate str (not "int") to str. Always convert with int() or float() before doing maths.

Multiple Inputs & split()

Sometimes you want the user to enter several values at once, separated by spaces or commas. Python's .split() combined with input() makes this clean and efficient.

multiple_inputs.py
PYTHON
# Method 1: separate input() calls (simple)
first_name = input("First name: ")
last_name  = input("Last name: ")
print(f"Full name: {first_name} {last_name}")

# Method 2: split() — user types "Ali Khan" in one input
first, last = input("Enter full name: ").split()
print(f"Hi {first}, surname is {last}")

# Method 3: map() — convert multiple values at once
# User types "10 20 30" → three integers
a, b, c = map(int, input("Enter 3 numbers: ").split())
print(f"Sum: {a + b + c}")  # Sum: 60

# User types "5 7" — two floats
x, y = map(float, input("Enter x y: ").split())
print(f"x² + y² = {x**2 + y**2:.2f}")

# Variable number of inputs → list
marks = list(map(int, input("Enter marks separated by spaces: ").split()))
print(f"Total: {sum(marks)}, Average: {sum(marks)/len(marks):.1f}")
💡
How map(int, iterable) works
map(func, iterable) applies func to every item in the iterable and returns a map object. map(int, ["10", "20", "30"]) is equivalent to calling int() on each element. Combined with .split() and tuple unpacking, it's the standard pattern for reading multiple numbers from one line.

Input Validation

Real programs can't trust users to type the right thing. Input validation means checking that the user's input is safe before you use it. Even a simple check with .isdigit() or a try/except block can prevent crashes.

input_validation.py
PYTHON
# Method 1: .isdigit() — check before converting
raw = input("Enter your age: ")
if raw.isdigit():
    age = int(raw)
    print(f"You are {age} years old.")
else:
    print("Please enter a valid whole number.")

# Method 2: try/except — handle errors gracefully
try:
    price = float(input("Enter price: "))
    print(f"Price: PKR {price:,.2f}")
except ValueError:
    print("Invalid! Please enter a number like 9.99")

# Method 3: strip() + check empty — common pattern
username = input("Enter username: ").strip()
if username:                   # truthy — non-empty string
    print(f"Welcome, @{username.lower()}!")
else:
    print("Username cannot be empty.")
Always .strip() text input
Users often accidentally add spaces before or after their input. input("Name: ").strip() removes leading/trailing whitespace so " Ali " becomes "Ali". Make it a habit for all text input — it prevents dozens of subtle bugs like failed string comparisons.

Building Interactive Programs

Combining print(), input(), variables, operators, and f-strings is all you need to build real interactive console programs. Let's look at three complete examples.

Example 1 — BMI Calculator

bmi_calculator.py
PYTHON
# ── BMI Calculator ───────────────────────────
print("=" * 35)
print("      BMI CALCULATOR")
print("=" * 35)

name   = input("Enter your name  : ").strip().title()
weight = float(input("Weight (kg)      : "))
height = float(input("Height (m)       : "))

bmi = weight / (height ** 2)

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25:
    category = "Normal weight"
elif bmi < 30:
    category = "Overweight"
else:
    category = "Obese"

print(f"""
─────────────────────────────────
  Result for: {name}
  BMI      : {bmi:.2f}
  Category : {category}
─────────────────────────────────""")

Example 2 — Currency Converter

currency_converter.py
PYTHON
# ── Currency Converter ───────────────────────
USD_TO_PKR = 278.50   # constant (rate)
USD_TO_GBP = 0.79
USD_TO_EUR = 0.92

print("Currency Converter (USD base)")
print("-" * 30)

amount = float(input("Enter amount in USD: $"))

print(f"""
  ${amount:.2f} USD equals:
  PKR {amount * USD_TO_PKR:,.2f}
  GBP {amount * USD_TO_GBP:.2f}
  EUR {amount * USD_TO_EUR:.2f}""")
📋
Pattern: Prompt → Validate → Convert → Use
Every interactive program follows: show prompt → get string → validate → convert type → compute → output. Internalise this flow and you can build anything.
🎨
Make output scannable
Use "=" * 30 for headers, "-" * 30 for dividers, aligned columns with f-string width formatting. Good output UX makes programs feel professional.
⌨️
Prompt text matters
Always tell the user what format you expect: "Enter height in metres (e.g. 1.75): " is far better than just "Height: ". Clear prompts reduce bad input.
🔒
Never trust raw input
Strip whitespace, check for empty strings, and use try/except around conversions. This is the foundation of defensive programming.
🧩 Knowledge Check
5 questions — test your mastery of Input & Output
1. What type does input() always return?
2. What does print("a", "b", "c", sep="-") output?
3. A user types 25 at an input() prompt. You then write age + 5. What happens?
4. What does print("Hi", end="") do differently from a normal print("Hi")?
5. Which line collects two integers from a single line of user input (e.g. user types 10 20)?
🏗️
Coding Challenge — Personal Finance Tracker
A complete interactive console app using everything from Phase 1
Task: Build a Personal Finance Tracker that:

1. Asks for the user's name (strip + title case it)
2. Asks for their monthly income (float)
3. Collects 3 expense amounts in a single input line (e.g. 8000 3500 2000) using map(float, ...split())
4. Calculates total expenses, savings, and savings rate %
5. Uses a comparison + logical operator to check if savings rate is healthy (≥ 20% AND savings > 0)
6. Prints a formatted report card with currency formatting (:,.2f) and a percentage (:.1f)
7. Prints a tip based on whether savings rate is healthy
💡 Show hints
  • Use e1, e2, e3 = map(float, input("Expenses: ").split())
  • Savings rate: (savings / income) * 100
  • Healthy check: rate >= 20 and savings > 0
  • Currency: f"PKR {income:,.2f}"
finance_tracker.py — Sample Solution
PYTHON
# ── Personal Finance Tracker ─────────────────
name   = input("Your name       : ").strip().title()
income = float(input("Monthly income  : "))

print("Enter 3 expenses separated by spaces:")
e1, e2, e3 = map(float, input("Expenses        : ").split())

total_exp   = e1 + e2 + e3
savings     = income - total_exp
savings_pct = (savings / income) * 100
is_healthy  = savings_pct >= 20 and savings > 0

tip = "✅ Great discipline! Keep saving." if is_healthy else "⚠️ Try to cut expenses and save ≥20%."

print(f"""
╔═══════════════════════════════════╗
  Finance Report — {name}
  ───────────────────────────────────
  Income       : PKR {income:,.2f}
  Expense 1    : PKR {e1:,.2f}
  Expense 2    : PKR {e2:,.2f}
  Expense 3    : PKR {e3:,.2f}
  ───────────────────────────────────
  Total Exp    : PKR {total_exp:,.2f}
  Savings      : PKR {savings:,.2f}
  Savings Rate : {savings_pct:.1f}%
  Healthy      : {is_healthy}
  ───────────────────────────────────
  Tip: {tip}
╚═══════════════════════════════════╝""")
🎉
Lesson 5 Complete!
Phase 1 is almost done! You have all the foundations. Time to apply everything in real mini projects.
← Course Home
Phase 1 · FoundationsLesson 5 of 6