Saltar al contenido
Back to home
Session 03 Python 2025-2026 1º

Functions, Validation, and Basic Persistence

Structuring programs with functions, robust validation, and basic data persistence using JSON files.

Key Concepts

  • Functions and return
  • Separation of responsibilities
  • Validation with try / except
  • Lists and controlled modification
  • Dictionaries as key-value structures
  • Introduction to JSON persistence
  • Difference between in-memory data and file-stored data

Mandatory Part

1. Modular Calculator

  • Each operation in a separate function
  • Main menu in another function
  • Main loop that allows repetition
  • Mandatory numeric input validation

Expected structure:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def menu():
    print("1. Add")
    print("2. Subtract")
    print("3. Exit")

2. Student Registration System

Program that:

  • Allows registering students

  • Each student will be a dictionary with:

    • name
    • age
    • grade

Store all students in a list.

Allow:

  1. Add student
  2. Show students
  3. Search student by name
  4. Exit

Additional requirements:

  • Validate that age and grade are numbers
  • Do not allow empty names
  • The program must be divided into functions

3. Statistics

Add a function that calculates:

  • Average grade
  • Highest grade
  • Lowest grade
  • Number of passing students

Without using max() or min() in the first version.


JSON Persistence

Objective: Save data so it is not lost when closing the program.

4. Save Students to a JSON File

  • Import json
  • Create a file called students.json
  • Save the student list using json.dump()

Base example:

import json

with open("students.json", "w") as file:
    json.dump(student_list, file, indent=4)

5. Load Students from File

When the program starts:

  • Try to read students.json
  • If it does not exist, start with an empty list
  • Use json.load()

Base example:

import json

try:
    with open("students.json", "r") as file:
        student_list = json.load(file)
except FileNotFoundError:
    student_list = []

6. Stronger error handling

Improve JSON loading to handle:

  • Missing file
  • Empty file
  • Corrupted JSON
  • Unexpected errors

Example:

try:
    with open("students.json", "r") as f:
        students = json.load(f)
except FileNotFoundError:
    students = []
except json.JSONDecodeError:
    students = []
    print("Corrupted file detected. Starting with empty list.")

Explain the difference between exception types.


7. Shopping List

  1. Read a JSON object
  2. Display menu
  • Add product
  • Remove product
  • Show products in the list
  • Check if product exists
  1. Save the JSON object with the changes made