Invert termination condition to continuation condition
Write the loop body
Update Loop Control Variable to reach termination
Subsection6.2.1WriteLoops-WE1-P1
ExercisesExercises
1.
Q1: Put the code in the right order to create a program that will calculate and print the sum of 10 natural numbers.
sum = 0
---
for i in range(0, 10):
---
sum += i
---
print(sum)
2.
Q2: Fill in the blanks in the following code to create a program that will print the even numbers between 1 and 20 (inclusive).
for x in range(__A__, __B__):
if ___C___ % ___D___ == ___E___:
print(___C___)
Blank A:
Blank B:
Blank C:
Blank D:
Blank E:
3.
Q3: Put the code in the right order to create a program that will generate an integer between 0 and 10,000 (inclusive), print the number, calculate and print the number of digits in the number.
import random
x = random.randint(0, 10000)
---
digits = 0
y = x
---
while y > 0:
---
digits += 1
y = y // 10
---
print(x, "has", digits, "digits.")
4.
Q4: Put the code in the right order to create a program that will print out all Armstrong numbers between 1 and 500. If the sum of the cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = (1*1*1) + (5*5*5) + (3*3*3)
for i in range(1, 500)
---
dig1 = i // 100
dig2 = (i // 10) % 10
dig3 = i % 10
---
total = dig1**3 + dig2**3 + dig3**3
---
if total == i:
---
print(i, "is an Armstrong number.")
5.
Q5: Put the code in the right order to create a program that will print out the squares and cubes of the first 10 natural numbers.
powers = [1, 2, 3]
---
for num in range(1, 11):
---
for power in powers:
---
print(num ** power, end=" ")
---
print()