Input, Output, Files and Validation
Getting Data In and Out
Every useful program exchanges data with the outside world. In Python, print() sends output to the screen and input() reads a value from the keyboard. These are the two most fundamental input/output operations. Beyond the keyboard, programs also read from and write to files — essential for storing data that persists between program runs.
# Basic input and output
name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello,", name, "- you will be", age + 1, "next year.")
The string passed to input() is the prompt — it appears on screen before the cursor so the user knows what to type. The function always returns a string, so numeric values must be converted with int() or float() before arithmetic can be performed.
CSV Files — Reading Comma-Separated Data
A CSV file (comma-separated values) stores tabular data as plain text. Each line is a row; values within a row are separated by commas. CSV is widely used because every spreadsheet application, database and programming language can read and write it. A student grade file might look like:
name,score,grade Ali Hassan,78,Pass Beth Clarke,92,Distinction Carlos Reyes,54,Pass
Python can read a CSV file using the built-in open() function. When you open a file, you specify a file mode: 'r' for reading, 'w' for writing (overwrites existing content), 'a' for appending (adds to the end). Once you have finished reading or writing, you must call the file’s close() method to close it.
Reading grades.csv line by line, splitting each line on commas:
f = open("grades.csv", "r")
header = f.readline() # Skip the header row
for line in f:
line = line.strip() # Remove trailing newline
fields = line.split(",")
name = fields[0]
score = int(fields[1])
grade = fields[2]
print(name, "-", score, "(" + grade + ")")
f.close()
Key steps: (1) open() opens the file in read mode. (2) .readline() reads and discards the header. (3) for line in f processes each remaining row. (4) .strip() removes the invisible \n at the end of each line. (5) .split(",") splits the line into a list of fields. (6) f.close() must be called once you have finished reading, to close the file. Instead of reading line by line, you could also use f.readlines(), which returns the whole file as a list of lines.
Creating a new CSV file and writing a header plus data rows:
f = open("results.csv", "w")
f.write("name,score\n") # Header row
students = [["Ali", 78], ["Beth", 92], ["Carlos", 54]]
for student in students:
f.write(student[0] + "," + str(student[1]) + "\n")
f.close()
Each row ends with \n (newline character) to move to the next line. Opening in "w" mode overwrites the file if it already exists. Use "a" mode to append new rows without deleting existing data. Once writing is finished, call f.close() to close the file. Instead of writing line by line, you could build a list of strings and write them all at once with f.writelines(list).
Validation Routines
Validation ensures that data entered by a user is reasonable before the program uses it. It does not guarantee the data is correct — a user could enter the wrong date of birth and it might still pass all checks — but it filters out obviously bad data. There are four types of validation check you need to know.
The four validation types are: presence check (is the field empty?), length check (is the data the right number of characters?), range check (is the value within acceptable numeric bounds?), and pattern check (does the data match an expected format?). A password system might use all four.
A presence check confirms that a field has been filled in:
username = input("Enter username: ")
if username == "":
print("Error: username cannot be empty")
A length check ensures the data is neither too short nor too long:
password = input("Enter password: ")
if len(password) < 8 or len(password) > 20:
print("Password must be 8 to 20 characters")
A range check tests whether a numeric value is within acceptable bounds:
age = int(input("Enter age: "))
if age < 0 or age > 120:
print("Age must be between 0 and 120")
Pattern Check
A pattern check verifies that data matches a particular format. This is the fourth of the four validation types named in the specification — it goes beyond simply checking whether a value is present, the right length or in range. A simple pattern check can be written using string operations to test the structure of data.
A simplified UK postcode check: with the space removed, a UK postcode is 5 to 7 characters long and starts with letters before digits. A basic pattern check might verify: no spaces, a length of 5 to 7 characters, and the first two characters are alphabetic:
postcode = input("Enter postcode (no spaces): ").upper()
def is_valid_postcode(code):
if len(code) < 5 or len(code) > 7:
return False
if not code[0].isalpha() or not code[1].isalpha():
return False
return True
if is_valid_postcode(postcode):
print("Valid format")
else:
print("Invalid postcode format")
Python’s .isalpha() returns True if all characters are alphabetic. .isdigit() returns True if all characters are digits. These built-in methods are enough for a simple pattern check — full regular expressions are not required in your exam.
Validation and authentication are not the same thing. Validation checks that data is in an acceptable format or range — it makes no claim about whether the data is true. Authentication verifies identity by checking credentials against a stored record. A program may need both: validate the password format first, then check it against the stored value.
Authentication
Authentication checks that a user’s identity matches a stored record. A simple authentication routine compares entered credentials against a list of known users:
# Simple authentication using parallel lists
users = [["admin", "pass123"], ["teacher", "gcse2026"]]
username = input("Username: ")
password = input("Password: ")
found = False
for user in users:
if user[0] == username and user[1] == password:
found = True
if found:
print("Access granted")
else:
print("Invalid credentials")