Loops

30 min
0/3 practice checks

A loop repeats work. A for loop walks over a range or a list:

total = 0
for i in range(1, 11):
    total = total + i
print(total)   # 55

range(1, 11) gives 1,2,…,10 (the stop value is excluded). A while loop repeats as long as a condition holds. Combine loops with if to count or filter.

Code practice

Use a for loop to add up the numbers 1 to 10 into a variable total (it should end at 55).

python

Runs in your browser. Charts (matplotlib) are not supported — use print-based output.

Code practice

Write count_evens(nums) that returns how many numbers in the list nums are even. (A number is even when n % 2 == 0.)

python

Runs in your browser. Charts (matplotlib) are not supported — use print-based output.

How many numbers does range(3) produce?