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)

The range() Function

Before looking at the For Loop itself, it’s worth understanding range() on its own, since it’s a built-in function used constantly with For Loops. range() generates a sequence of numbers, and it does not create a full list in memory — it produces numbers one at a time as needed, which makes it memory-efficient even for very large ranges.

range() accepts up to three arguments: range(start, stop, step)

1
2
3
4
print(list(range(5)))          # [0, 1, 2, 3, 4]        -> stop only: starts at 0, stops BEFORE 5
print(list(range(3, 10))) # [3, 4, 5, 6, 7, 8, 9] -> start and stop: starts at 3, stops BEFORE 10
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8] -> start, stop, step: counts by 2
print(list(range(10, 0, -1))) # [10, 9, 8, ..., 1] -> negative step: counts backward

Key points:

  • The stop value is never included in the result — range(5) goes up to 4, not 5.
  • Wrapping range() in list(...) above is only to visualize its contents; in a For Loop, you use range() directly without list(), as shown below.

Here is an example implementation of a For Loop using the range function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
## For in Range
# Syntax Type 1:
for i in range(5): # 5 is End Value | When i in range of 0~4
print("This Iteration number " + str(i))

print("\n")

# Syntax Type 2:
for i in range(3,10): # 3 is Start Value, 10 is End Value | When i in range 3~9
print("This Iteration number " + str(i))

print("\n")

# Syntax Type 3:
for i in range(20,5,-1): # 20 is Start Value, 5 is End Value, and the difference is -1 |
# When i is in the range 20~6, subtract 1 on each iteration
print("This Iteration number " + str(i))

Here is an example implementation of a For Loop using a standard data structure:

1
2
3
4
5
6
7
8
9
10
11
## For in Standard
## Used when you have data in the form of a list/array.

## List/Array
## A collection of data items (usually of the same type, but there can also be mixed types).
## You can declare a list using [], and each item is separated by a comma (,).

str_belanja = ["White Cabbage", "Chicken", "Beef", "Shoyu", "Sweet Soy Sauce", "Indomie"]

for i in str_belanja:
print(i)

List Comprehension & enumerate() (Modern Loop Idioms)

Professional Python code often avoids writing out a full for loop just to build a new list. A list comprehension does this in one line and is the idiomatic (Pythonic) way to transform or filter a list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
numbers = [1, 2, 3, 4, 5]

# Traditional loop
squares = []
for n in numbers:
squares.append(n * n)

# List comprehension (preferred, more concise)
squares = [n * n for n in numbers]

# List comprehension with a condition (only even numbers)
even_only = [n for n in numbers if n % 2 == 0]

print(squares)
print(even_only)

When you need both the index and the value while looping through a list, use enumerate() instead of manually tracking a counter variable:

1
2
3
4
str_belanja = ["White Cabbage", "Chicken", "Beef"]

for index, item in enumerate(str_belanja):
print(f"{index}: {item}")

Output:

1
2
3
0: White Cabbage
1: Chicken
2: Beef

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:

  1. Conditional Version
  2. 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
2
3
4
5
i = 0
while(i < 5):
print("This Iteration number " + str(i))
i = i + 1
#i += 1

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:

  1. continue (to skip the current iteration and continue with the next one)
  2. break (to forcefully exit the loop)

Here’s an example of how to use them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Without Keyword Version
status = True
i = 0
a = int(input("Enter max value: "))

while(status):
if (i < a):
print("This Iteration number " + str(i))
i += 1
else:
print("Program has Ended")
status = False

# With Keyword Version
i = 0
a = int(input("Enter max value: "))

while(True):
if (i < a):
print("This Iteration number " + str(i))
i += 1
continue
else:
print("Program has Ended")
break

Exercise

Complete the following exercises to test your understanding of Control Structures II.

EXERCISE FOR LOOP

EXERCISE FOR LOOP 1

Create a program that generates a triangle pyramid of numbers based on user input, like the example output below.

OUTPUT

1
2
3
4
5
6
7
8
9
Input Max Value: 7 (Input by User)

7777777
666666
55555
4444
333
22
1

EXERCISE FOR LOOP 2

Create a program that generates a triangle pyramid of numbers based on user input, like the example output below.

OUTPUT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Input Max Value: 7 (Input by User)

7777777
666666
55555
4444
333
22
1
22
333
4444
55555
666666
7777777

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
2
3
4
5
6
7
8
9
10
Enter any number: 5 (Input by User)
The number 5 is odd
Do you want to repeat? Y (Input by User)

Enter any number: 8 (Input by User)
The number 8 is even
Do you want to repeat? N (Input by User)

Program Stops
Thank you for using my program ^^

EXERCISE WHILE LOOP 2

Create a program to filter triangles based on the previous module’s exercise using a loop.

OUTPUT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Enter Side A: 5 (Input by user)
Enter Side B: 5 (Input by user)
Enter Side C: 5 (Input by user)

It is an Equilateral Triangle

Do you want to repeat? Y (Input by User)

Enter Side A: 5 (Input by user)
Enter Side B: 5 (Input by user)
Enter Side C: 7 (Input by user)

It is an Isosceles Triangle

Do you want to repeat? N (Input by User)

Program Stops
Thank you for using my program ^^

EXERCISE WHILE LOOP 3

Create a function program to calculate the average grade based on the letter categories entered by the user, 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
2
3
4
5
6
Enter Grade Category (Press Enter to Stop): A (Input by User) // 4
Enter Grade Category (Press Enter to Stop): B (Input by User) // 3
Enter Grade Category (Press Enter to Stop): B (Input by User) // 3
Enter Grade Category (Press Enter to Stop): C (Input by User) // 2
Enter Grade Category (Press Enter to Stop): (Input by User) //(4 + 3 + 3 + 2)/4 = 3
The average grade is 3.00 with a designation of B