Area 2.5

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.

3
I/O Methods
5
File Modes
~2hrs
Study Time

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()
Get string input from user
name = input("Enter your name: ")
int(input())
Get integer input
age = int(input("Enter age: "))
float(input())
Get decimal 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()
Display text to screen
print("Hello World")
print(f"")
Formatted string output
print(f"Age: {age}")
print(, sep=)
Custom separator
print(a, b, c, sep="-")
print(, end=)
Custom line ending
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)
Open file for reading/writing
file = open("data.txt", "r")
file.read()
Read entire file content
content = file.read()
file.readline()
Read one line
line = file.readline()
file.write(text)
Write text to file
file.write("Hello\n")
file.close()
Close file properly
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 newline

Best 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"Read

Open for reading (default)

File must exist

"w"Write

Open for writing (overwrites existing)

Creates new file if needed

"a"Append

Open for writing (adds to end)

Preserves existing content

"x"Exclusive

Create new file (fails if exists)

Prevents accidental overwrite

"r+"Read/Write

Open 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

Project
45 minutes

Create a program that takes user input and performs calculations with error handling

File Data Processor

Practice
40 minutes

Read data from a text file, process it, and write results to another file

Input Validation Workshop

Validation
35 minutes

Implement robust input validation for different data types and ranges