Algorithms and Programming Python 4
Control Structure II
Looping
Looping, or iteration, is a program structure that causes repeated execution of a block of code. There are two types of loops:
- Loops with a known number of iterations (For Loop)
- Loops with an unknown number of iterations (While Loop)
For Loop
A For Loop is typically used when the number of iterations is known. There are two types of For Loops in Python:
- For in range (This loop uses a range of numbers to determine how many times the loop will execute)
- For in standard (This loop uses a data structure like a list or array to determine how many times it will execute)
Here is an example implementation of a For Loop using the range function:
1 | ## For in Range |
Here is an example implementation of a For Loop using a standard data structure:
1 | ## For in Standard |
While Loop
A While Loop is a type of loop that is activated using a boolean condition. It is typically used when the number of iterations is not known. There are two versions of the while loop:
- Conditional Version
- Keyword Version
The conditional version is used when we want to repeat a loop based on a condition that we set ourselves. Its usage is not much different from a Conditional IF statement. Here’s an example:
1 | i = 0 |
The Keyword Version relies on keywords to stop or continue the loop, which can be risky and may cause an infinite loop if not used carefully.
There are two keywords used within a while loop:
- continue (to skip the current iteration and continue with the next one)
- break (to forcefully exit the loop)
Here’s an example of how to use them:
1 | # Without Keyword Version |
Exercise
Complete the following exercises to test your understanding of Control Structures II.
EXERCISE FOR LOOP
EXERCISE FOR LOOP 1
Create a program to create a triangle pyramid number from the user input like this example of output.
OUTPUT
1 | Input Max Value: 7 (Input by User) |
EXERCISE FOR LOOP 2
Create a program to create a triangle pyramid number from the user input like this example of output.
OUTPUT
1 | Input Max Value: 7 (Input by User) |
EXERCISE WHILE LOOP
EXERCISE WHILE LOOP 1
Create a program to filter odd and even numbers based on the previous module's exercise using a loop.
OUTPUT:
1 | Enter any number: 5 (Input by User) |
EXERCISE WHILE LOOP 2
Create a program to filter triangles based on the previous module's exercise using a loop.
OUTPUT
1 | Enter Side A: 5 (Input by user) |
EXERCISE WHILE LOOP 3
Create a function program to calculate the average grade based on the letter categories inputted, with the following rules:
A = 4.00
A- = 3.75
B+ = 3.50
B = 3.00
B- = 2.75
C+ = 2.50
C = 2.00
C- = 1.75
D = 1.50
E = 1.20
OUTPUT:
1 | Enter Grade Category (Press Enter to Stop): A (Input by User) // 4 |


