9. Input & Output (I/O)
Connecting your program to the world
Input is how your program receives information from the outside world. In Python, the input() function pauses execution and waits for the user to type something:
# Basic input name = input('What is your name? ') print(f'Hello, {name}!') # IMPORTANT: input() always returns a string # You must convert to numbers if needed age_str = input('How old are you? ') age = int(age_str) # Convert to integer # Or in one line: score = float(input('Enter your score: ')) if age >= 18: print('You are an adult.')
Displaying Output
You've used print() from the start, but it has more power than you've seen:
# Multiple items print('Name:', 'Ama', 'Age:', 22) # Custom separator print('2025', '06', '15', sep='-') # 2025-06-15 # No newline at end print('Loading', end='') print('...', end='') print(' Done!') # Loading... Done! # f-strings for formatted output price = 49.5 print(f'Price: GHS {price:.2f}') # GHS 49.50 quantity = 1234567 print(f'Units sold: {quantity:,}') # 1,234,567
File Handling
File handling lets your program read from and write to files on disk — making data persist beyond the life of the program. Python makes this clean and safe with the with statement.
Reading Files
# Read entire file with open('data.txt', 'r') as file: content = file.read() print(content) # Read line by line (memory-efficient for large files) with open('data.txt', 'r') as file: for line in file: print(line.strip()) # Read all lines into a list with open('data.txt', 'r') as file: lines = file.readlines()
Writing Files
# Write to a file (overwrites if exists) with open('output.txt', 'w') as file: file.write('Hello, File World!\n') file.write('Line 2\n') # Append to a file (adds to end, preserves existing) with open('log.txt', 'a') as file: file.write('User logged in at 09:00\n') # Write multiple lines at once students = ['Ama', 'Kofi', 'Abena'] with open('students.txt', 'w') as file: file.writelines([s + '\n' for s in students])
Always use `with open(...)` for file operations. It automatically closes the file when you're done — even if an error occurs. Unclosed files can cause data loss and resource leaks.
Working with External Data
CSV (Comma-Separated Values) files are the most common format for data exchange. Python's csv module makes them easy to work with:
import csv # Writing CSV data = [ ['Name', 'Score', 'Grade'], ['Ama', 95, 'A'], ['Kofi', 78, 'B'], ['Abena', 88, 'B+'] ] with open('grades.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data) # Reading CSV with open('grades.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(f"{row['Name']} scored {row['Score']}")
Knowledge Check
Ready to test your understanding of 9. Input & Output (I/O)?