Back

Some useful operations using for

Q1. Look at the following code. Can you predict what should get printed? Type in this code and run it. What happened?

'''This program adds up the
numbers in a list using a for loop
to iterate through the list.'''

data = [1, 5, 4, 10, 20]

for banana in data:
    total = total + banana

print("The total is:", total)

Q2. Because total had not been defined before you tried to add it to the value in the variable called banana, Python was unhappy so it gave you an error. Initialise the variable called total, like this and run your code again. It should tell you what the total of the numbers in the list is.

data = [1, 5, 4, 10, 20]

total = 0
for banana in data:
    total = total + banana

print("The total is:", total)

Q3. Add a comment block at the top of the program, to say what the program does.
Q4. Using banana as an index value may seem strange, but I can use any valid name I like. It's always best, however, to try and use meaningful names. This helps your code to read better. Change banana into a more helpful name.
Q5. Using the range keyword, add up the even numbers between 1 and 10 inclusive and display the result.
Q6. Modify the above program so you add up the even numbers between 1 and 1 000 000 and display the result.
Q7. Write a program to print out the numbers from 1 to 10 inclusive, along with their squares and their cubes.
Q8. Write a program to print out the numbers that are divisible by 5 between 1 and a 100 inclusive,
Q9. Write a program to print out the numbers that are divisible by 17 between 1 and a 200 inclusive,
Q10.
Modify Q9 so that it also prints out how many numbers were divisible by 17.

Back