Last time, we used while and for to repeat actions and print structured outputs like tables. Now students try to finish the following practice to review what we learned last unit:
N, and calculates the sum 1 + 2 + 3 + ... + N using both a for loop and a while loop. Then print the total result for each method.Output example:
Enter a positive integer N: 5
Sum using for loop = 15
Sum using while loop = 15
Answer example:
# --- For loop version ---
N = int(input("Enter a positive integer N: "))
total_for = 0
for i in range(1, N + 1):
total_for += i
print("Sum using for loop =", total_for)
# --- While loop version ---
total_while = 0
x = 1
while x <= N:
total_while += x
x += 1
print("Sum using while loop =", total_while)
But when we need to store a collection of related values, such as all students’ names, daily expenses for a week, or a shopping list—one variable isn’t enough. Creating many variables (name1, name2, name3...) is messy and hard to maintain. Today we’ll learn Lists, a new data structure. Think of a list as a box that holds many items together inside square brackets [ ]. With lists, we can store, access, and modify a whole group of data, and combine them with loops to build smarter programs.