Python Basics — Input/Output Practice Exercises

3 minute read

Input/Output Practice Exercises

Test your understanding of print(), input(), string formatting, and format specifiers.


Exercise 1: Greeting Card

Write a program that asks for a person’s name and age, then prints a formatted greeting card with a decorative border.

Expected Output:

Enter name: Alice
Enter age: 25

**************************
*   Happy Birthday!      *
*   Dear Alice           *
*   Turning 25 today!    *
**************************
Solution
name = input("Enter name: ")
age = input("Enter age: ")

width = 26
print()
print("*" * width)
print(f"*{'Happy Birthday!':^24}*")
print(f"*{'Dear ' + name:^24}*")
print(f"*{'Turning ' + age + ' today!':^24}*")
print("*" * width)

Exercise 2: Receipt Formatter

Create a program that formats a simple receipt. Use right-aligned prices and a total with 2 decimal places.

Given data:

items = [
    ("Coffee", 4.50),
    ("Sandwich", 8.99),
    ("Cookie", 2.75),
]
tax_rate = 0.08

Expected Output:

========== RECEIPT ==========
Coffee                  $4.50
Sandwich                $8.99
Cookie                  $2.75
-----------------------------
Subtotal               $16.24
Tax (8.0%)              $1.30
=============================
TOTAL                  $17.54
Solution
items = [
    ("Coffee", 4.50),
    ("Sandwich", 8.99),
    ("Cookie", 2.75),
]
tax_rate = 0.08

width = 29

print(f"{'RECEIPT':=^{width}}")
for name, price in items:
    print(f"{name:<20} ${price:>5.2f}")

subtotal = sum(price for _, price in items)
tax = subtotal * tax_rate
total = subtotal + tax

print("-" * width)
print(f"{'Subtotal':<20} ${subtotal:>5.2f}")
print(f"{'Tax (' + f'{tax_rate:.1%}' + ')':<20} ${tax:>5.2f}")
print("=" * width)
print(f"{'TOTAL':<20} ${total:>5.2f}")

Exercise 3: Number Base Converter

Write a program that takes a decimal number from the user and displays it in binary, octal, and hexadecimal with proper prefixes.

Expected Output:

Enter a number: 255

Number: 255
Binary:  0b11111111
Octal:   0o377
Hex:     0xff
Solution
num = int(input("Enter a number: "))

print(f"\nNumber: {num}")
print(f"Binary:  {num:#b}")
print(f"Octal:   {num:#o}")
print(f"Hex:     {num:#x}")

Exercise 4: Student Report Card

Given student data, display a neatly formatted report card using a table with alignment and format specifiers.

Given data:

student = "John Smith"
subjects = [
    ("Mathematics", 92),
    ("Science", 87),
    ("English", 95),
    ("History", 78),
    ("Art", 88),
]

Expected Output:

=== Report Card: John Smith ===

Subject         Score   Grade
------------------------------
Mathematics        92   A
Science            87   B+
English            95   A
History            78   C+
Art                88   B+
------------------------------
Average          88.0   B+
Solution
student = "John Smith"
subjects = [
    ("Mathematics", 92),
    ("Science", 87),
    ("English", 95),
    ("History", 78),
    ("Art", 88),
]

def get_grade(score):
    if score >= 90: return "A"
    elif score >= 85: return "B+"
    elif score >= 80: return "B"
    elif score >= 75: return "C+"
    elif score >= 70: return "C"
    else: return "D"

print(f"=== Report Card: {student} ===\n")
print(f"{'Subject':<15} {'Score':>5}   {'Grade'}")
print("-" * 30)

for subject, score in subjects:
    grade = get_grade(score)
    print(f"{subject:<15} {score:>5}   {grade}")

avg = sum(s for _, s in subjects) / len(subjects)
print("-" * 30)
print(f"{'Average':<15} {avg:>5.1f}   {get_grade(avg)}")

Exercise 5: Mini Calculator with Formatted Output

Build a calculator that takes two numbers and an operator from the user, performs the calculation, and displays the result with appropriate formatting (2 decimal places for division, commas for large numbers).

Expected Output:

Enter first number: 1500000
Enter operator (+, -, *, /): *
Enter second number: 3.5

Calculation: 1,500,000 * 3.5
Result: 5,250,000.00
Solution
num1 = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if op == "+":
    result = num1 + num2
elif op == "-":
    result = num1 - num2
elif op == "*":
    result = num1 * num2
elif op == "/":
    if num2 == 0:
        print("Error: Division by zero!")
        exit()
    result = num1 / num2
else:
    print(f"Unknown operator: {op}")
    exit()

# Format input numbers — show as int if whole
def fmt(n):
    return f"{int(n):,}" if n == int(n) else f"{n:,}"

print(f"\nCalculation: {fmt(num1)} {op} {fmt(num2)}")
print(f"Result: {result:,.2f}")

Scoring Guide

Exercises Completed Level
5/5 Expert — Input/Output mastered!
4/5 Advanced — Solid formatting skills
3/5 Intermediate — Good foundation
1-2/5 Beginner — Review formatting concepts

Next Chapter: Control Flow →

Updated: