Input and Output
Learn to handle data exchange between your programs and the outside world through keyboard input, screen output, and file operations with proper error handling.
Learning Objectives
- Handle keyboard input from users effectively
- Display formatted output to the screen
- Perform file operations: open, read, write, and close
- Implement proper error handling for I/O operations
- Apply input validation techniques for user data
Input/Output Methods
Keyboard Input
Getting data from the user through keyboard entry
Key Functions:
input()name = input("Enter your name: ")int(input())age = int(input("Enter age: "))float(input())price = float(input("Enter price: "))Python Examples:
# Basic input
name = input("What's your name? ")
print(f"Hello, {name}!")
# Numeric input with conversion
try:
age = int(input("How old are you? "))
print(f"You are {age} years old")
except ValueError:
print("Please enter a valid number")
# Multiple inputs on one line
x, y = input("Enter two numbers: ").split()
x, y = int(x), int(y)Best Practices:
- Always provide clear prompts
- Validate input before using
- Handle conversion errors gracefully
- Use try-except for numeric conversions
Screen Output
Displaying information to the user on screen
Key Functions:
print()print("Hello World")print(f"")print(f"Age: {age}")print(, sep=)print(a, b, c, sep="-")print(, end=)print("Hello", end=" ")Python Examples:
# Basic output
print("Welcome to the program!")
print() # Empty line
# Formatted output
name = "Alice"
score = 95.7
print(f"Student: {name}, Score: {score:.1f}%")
# Multiple values
print("Values:", 10, 20, 30, sep=" | ", end="\n\n")
# Formatting numbers
pi = 3.14159
print(f"Pi to 2 decimal places: {pi:.2f}")Best Practices:
- Use f-strings for formatting
- Format numbers appropriately
- Add spacing for readability
- Use meaningful output messages
File Operations
Reading from and writing to text files for data persistence
Key Functions:
open(file, mode)file = open("data.txt", "r")file.read()content = file.read()file.readline()line = file.readline()file.write(text)file.write("Hello\n")file.close()file.close()Python Examples:
# Reading from file
try:
with open("input.txt", "r") as file:
content = file.read()
print("File contents:", content)
except FileNotFoundError:
print("File not found!")
# Writing to file
data = ["Alice", "Bob", "Charlie"]
with open("output.txt", "w") as file:
for name in data:
file.write(f"{name}\n")
# Reading line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip()) # Remove newlineBest Practices:
- Use "with" statement for automatic closing
- Handle FileNotFoundError exceptions
- Choose appropriate file modes (r, w, a)
- Strip whitespace when reading lines
File Access Modes
"r"ReadOpen for reading (default)
File must exist
"w"WriteOpen for writing (overwrites existing)
Creates new file if needed
"a"AppendOpen for writing (adds to end)
Preserves existing content
"x"ExclusiveCreate new file (fails if exists)
Prevents accidental overwrite
"r+"Read/WriteOpen for both reading and writing
File must exist
Common I/O Errors & Solutions
ValueError
Cause:
Invalid conversion (e.g., int("hello"))
Solution:
Use try-except blocks for input conversion
Example:
try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid number format")FileNotFoundError
Cause:
Attempting to read non-existent file
Solution:
Check file existence or use try-except
Example:
try:
with open("file.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("File not found")PermissionError
Cause:
Insufficient permissions to access file
Solution:
Check file permissions or handle gracefully
Example:
try:
with open("protected.txt", "w") as f:
f.write("data")
except PermissionError:
print("Permission denied")Learning Activities
Interactive Calculator
Create a program that takes user input and performs calculations with error handling
File Data Processor
Read data from a text file, process it, and write results to another file
Input Validation Workshop
Implement robust input validation for different data types and ranges