Input & Output
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.
| Parameter | Default | Purpose |
|---|---|---|
| *objects | — | One or more values to print, separated by commas |
| sep | " " (space) | String placed between multiple values |
| end | "\n" (newline) | String printed after the last value |
| file | sys.stdout | Where to write output (advanced — file objects) |
| flush | False | Force immediate output (advanced — buffering) |
# 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()
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.
input()input() returns the stringstr — even if the user typed 42.# 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
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.
# 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}")
map(int, iterable) worksmap(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.
# 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.")
.strip() text inputinput("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 ─────────────────────────── 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 ─────────────────────── 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}""")
"=" * 30 for headers, "-" * 30 for dividers, aligned columns with f-string width formatting. Good output UX makes programs feel professional."Enter height in metres (e.g. 1.75): " is far better than just "Height: ". Clear prompts reduce bad input.try/except around conversions. This is the foundation of defensive programming.input() always return?print("a", "b", "c", sep="-") output?25 at an input() prompt. You then write age + 5. What happens?print("Hi", end="") do differently from a normal print("Hi")?10 20)?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}"
# ── 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} ╚═══════════════════════════════════╝""")