Input and Output
beginner25 minLearning objectives
- Obtain user input from the keyboard
- Display formatted output
- Read data from text files
- Write data to text files
Learn
AQA 4.1.1.8 — Keyboard input, screen output, file input, file output
Retrieval: you've been using input() and print() since the very first lesson of this course without a dedicated explanation - this lesson makes that knowledge explicit and extends it to files.
Keyboard input and screen output
name = input("Enter your name: ")
score = int(input("Enter your score: "))
print(f"{name} scored {score}.")
input() always returns a string — convert it with int() or float() if you need a number.
Writing to a file
with open("scores.txt", "a") as f:
f.write(f"{name},{score}\n")
"a" (append) adds to the end of the file without erasing what's there; "w" (write) would overwrite it. The with statement automatically closes the file afterwards, even if an error occurs.
Reading from a file
with open("scores.txt", "r") as f:
for line in f:
student, mark = line.strip().split(",")
print(f"{student}: {mark}")
.strip() removes the trailing newline; .split(",") breaks the line into its comma-separated fields.
Worked example — a student record logger
def log_result(name, score):
with open("results.txt", "a") as f:
f.write(f"{name},{score}\n")
def show_all_results():
with open("results.txt", "r") as f:
for line in f:
name, score = line.strip().split(",")
print(f"{name}: {score}")
This mirrors a real SOW practical task — a Student Record Logger that stores and retrieves names and assessment scores from text files.
Reflection
What would go wrong if you opened the file with "w" instead of "a" inside log_result, and called it twice in a row for two different students?