Loops & Lists — From Variables to Student Records
Introduce `for` loops and Python lists; refactor a student “mini-automation” from many variables to list-based data.
Learning Objectives
- Iterate with
forloops usingrange()and direct iteration over sequences. - Create and manipulate Python lists: indexing, slicing,
len(),append,insert,remove,pop. - Recognize the limitations of “one-variable-per-student” and refactor to list-based structures.
- Use parallel lists (e.g.,
names,surnames,grades) and iterate over them (withrangeorzip).
Session Plan (theory)
- Motivation: the scaling problem
- Naive approach:
name1 = "Ali"; surname1 = "Yılmaz"; grade1 = 86 name2 = "Ayşe"; surname2 = "Demir"; grade2 = 92 # … quickly becomes unmanageable as student count grows - Why this doesn’t scale; benefits of sequences.
- Naive approach:
-
forloops- Iterating with
for x in sequence:vsfor i in range(n):. - Off-by-one pitfalls;
range(start, stop, step).
- Iterating with
- Lists
- Creating lists; indexing & slicing;
len(). - Adding/removing items:
append,insert,remove,pop. - Iterating over values and over indices; using
zipfor parallel lists.
- Creating lists; indexing & slicing;
- Parallel lists for simple records
-
names = [...],surnames = [...],grades = [...]. - Printing aligned rows; computing statistics (min, max, average).
-
Hands-on
- Mini Project: Student Registry v1 (Lists & Loops)
- Start from an empty repo folder or continue last week’s.
- Build three lists:
names,surnames,grades(seed a few entries). - Tasks:
- Print all students as
# index - Full Name - Grade. - Compute class size, average grade, best/worst grade (show name + value).
- Add a new student (append to each list) and reprint the table.
- Remove a student by index (use
pop) and reprint. - Bonus: use
zip(names, surnames, grades)to print full rows without indices.
- Print all students as