A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.
A for loop is like 'do this for each...' โ for each student in the class, print their name. For each number from 1 to 10, add it to the total.
Showing a random 20 of 50 problems.
Example 1
easy
What does `range(2, 6)` produce?
Example 2
easy
Trace: `total=0; for i in range(5): total+=2`. Final total?
Example 3
medium
Trace: `total=0; for i in range(1,11): if i==7: break; total+=i`. Final total?
Example 4
easy
Why might `for i in range(1, 5)` instead of `for i in range(5)` be the better choice?
Example 5
medium
Trace: `total=0; for i in range(2,8): total+=i`. Final total?
Example 6
medium
Trace: `nums=[3,1,4,1,5]; mx=nums[0]; for x in nums[1:]: if x>mx: mx=x`. Final mx?
Example 7
medium
Trace nested: `c=0; for i in range(4): for j in range(3): c+=1`. Final c?
Example 8
medium
Trace: `out=[]; for i in range(4): out.append(i*(i+1))`. Final out?
Example 9
medium
Trace: `p=1; for i in range(1,6): if i%2==0: p*=i`. Final p?
Example 10
medium
Convert this FOR loop to a WHILE loop: FOR i = 1 TO 5: OUTPUT i.
Example 11
medium
Trace: `s=0; for i in range(1,6): for j in range(1,i+1): s+=j`. Final s?
Example 12
medium
Trace: `out=[]; for i in range(5): if i%2: out.append(i)`. Final out?
Example 13
easy
What values does `range(10, 0, -2)` produce?
Example 14
challenge
A for loop over a list of n items contains another for loop over the same list. Each iteration does O(1) work. What is the total time complexity in terms of n?
Example 15
easy
Trace: `count=0; for x in [2,4,6,8]: if x%2==0: count+=1`. Final count?
Example 16
hard
Trace: `n=5; out=[]; for i in range(n): row=[]; for j in range(n): row.append(1 if i==j else 0); out.append(row)`. How many 1s in out?
Example 17
medium
What does this code output?
SET scores = [85, 92, 78, 95, 88]
SET highest = scores[0]
FOR i = 1 TO LENGTH(scores) - 1
IF scores[i] > highest THEN
SET highest = scores[i]
END IF
END FOR
OUTPUT highest
Example 18
easy
Trace: `total=0; for i in range(4): total+=i`. Final total?
Example 19
easy
Trace: `out=[]; for x in [3,1,4]: out.append(x+1)`. Final out?
Example 20
medium
When is a `while` loop preferable to a `for` loop?