Course topics

By WebNest Studio

Python Tutorial

Input and Output in Python

Most programs need to talk to the user: read values they type and show results in a readable way. Python's input() reads a line from the keyboard and print() writes to the screen, while f-strings and format specifiers make output look professional.

This lesson covers reading input and converting it to numbers, validating input, reading several values from one line, and formatting output with widths, alignment and decimal places.

Reading Input

input(prompt) shows the prompt, waits for the user to press Enter, and returns what they typed as a string — always a string, even if they typed digits. Convert it with int() or float(). Conversion of invalid text raises ValueError, so real programs validate input in a loop with try/except.

Multiple Values

To read several values from one line, split the string: a, b = input().split(), and convert with map(int, input().split()). This pattern is common in coding challenges.

Formatting Output

f-strings (f"{value}") insert values into text. After a colon you can add a format specifier: {price:.2f} (two decimals), {n:,} (thousands separator), {name:<10} / {name:>10} / {name:^10} (left/right/centre align in 10 characters), {ratio:.1%} (percentage), and {value=} (prints the expression and its value, great for debugging).

Examples

Reading input and converting it

Python
name = input("Your name: ")
age = int(input("Your age: "))
print(f"Hello {name}, next year you will be {age + 1}.")
Output
Your name: Your age: Hello Asha, next year you will be 25.

Reading several numbers from one line

Python
a, b, c = map(int, input("Enter three marks: ").split())
print("Total:", a + b + c)
print("Average:", (a + b + c) / 3)
Output
Enter three marks: Total: 255
Average: 85.0

Validating input with a loop

Python
while True:
    text = input("Quantity (1-10): ")
    try:
        quantity = int(text)
    except ValueError:
        print(f"'{text}' is not a whole number.")
        continue
    if 1 <= quantity <= 10:
        break
    print("Please enter a number between 1 and 10.")

print("You ordered", quantity)
Output
Quantity (1-10): 'five' is not a whole number.
Quantity (1-10): Please enter a number between 1 and 10.
Quantity (1-10): You ordered 3

Formatting a neat report

Python
items = [("Python course", 1, 2999), ("Workbook", 3, 499.5), ("Stickers", 10, 25)]

print(f"{'Item':<15}{'Qty':>5}{'Amount':>12}")
print("-" * 32)
total = 0
for name, qty, price in items:
    amount = qty * price
    total += amount
    print(f"{name:<15}{qty:>5}{amount:>12,.2f}")
print("-" * 32)
print(f"{'Total':<20}{total:>12,.2f}")
print(f"{0.1845:.1%} of students scored above 90")
print(f"{total=}")
Output
Item             Qty      Amount
--------------------------------
Python course      1    2,999.00
Workbook           3    1,498.50
Stickers          10      250.00
--------------------------------
Total                   4,747.50
18.4% of students scored above 90
total=4747.5

Common Mistakes

  • Doing arithmetic on input() without converting: "5" + "3" gives "53".
  • Crashing on invalid input instead of validating with try/except.
  • Using float for money and printing raw values like 0.30000000000000004 instead of formatting.
  • Building output with + and str() everywhere instead of f-strings.

Key Points to Remember

  • input() always returns a string; convert with int() or float().
  • Validate input in a loop with try/except ValueError.
  • map(int, input().split()) reads several numbers from one line.
  • f-string format specifiers control decimals, alignment, separators and percentages.
  • f"{expr=}" prints an expression and its value for quick debugging.

Practice the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.