Back

Some useful operations using for - Answers

Q1. 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.

Q2. Initialise total and the program will run.

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

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

print("The total is:", total)

Q3. Use triple quotes to enclose a block of comments.
Q4. E.g. use item:

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

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

       print("The total is:", total)

Q5. Even numbers between 1 and 10 inclusive and display the result:

total = 0
for banana in range(2,11,2):
     total = total + banana

print("The total is:", total)

Q6. To add up the even numbers between 1 and 1 000 000 and display the result:

print('\n\n')
total = 0
for banana in range(2,1000001,2):
    total = total + banana

print("The total is:", total)

Q7. A program to print out the numbers from 1 to 10 inclusive, along with their squares and their cubes:

for fishfingers in range(1,11):
    print(fishfingers,fishfingers**2,fishfingers**3)

Q8. Write a program to print out the numbers that are divisible by 5 between 1 and a 100 inclusive,

for num in range(1,101):
    if num%5==0:
        print(num)

Q9 - Q10 . A program to print out the numbers that are divisible by 17 between 1 and a 200 inclusive and also prints out how many numbers were divisible by 17:

print('\n')
count=0
for num in range(1,201):
    if num%17==0:
        print(num)
        count+=1

print('\n')
print(count, 'numbers were divisible by 17.')

Back