2.5.1 Implementing input and output

2.5.1 Implementing input and output

Keyboard Input
Purpose: Accept data entered by the user.

When used: To gather user input during program execution.

Python example:

name = input("Enter your name: ")
print("Hello", name)
        
Screen Output
Purpose: Display information to the user.

When used: To show results, messages, or errors.

Python example:

total = 25
print("The total is:", total)
        
Text File Input and Output
Purpose: Store and retrieve data permanently.

When used: For saving results or reading stored data.

2.5.2 Using text files for input and output

Opening a File for Reading
Python example:

file = open("data.txt", "r")
content = file.read()
file.close()

print(content)
        
Opening a File for Writing
Python example:

file = open("output.txt", "w")
file.write("Hello, file!")
file.close()
        
Writing Multiple Lines to a File
Python example:

file = open("numbers.txt", "w")

for i in range(1, 6):
    file.write(str(i) + "\n")

file.close()
        

2.5.3 Interpreting code using input and output

Interpreting I/O Code
Interpreting code means understanding how data flows into and out of a program.

Example:

age = int(input("Enter your age: "))
print(age + 1)
        
This code reads a value from the keyboard, converts it, and outputs a result.

2.5.4 Creating code using input and output

Creating I/O Code
Python example:

price = float(input("Enter price: "))
quantity = int(input("Enter quantity: "))

total = price * quantity
print("Total cost:", total)
        

2.5.5 Debugging code using input and output

Debugging I/O Code
Incorrect code:

number = input("Enter a number: ")
print(number + 5)
        
Problem: Input is a string, not a number.

Corrected code:

number = int(input("Enter a number: "))
print(number + 5)