Rebirth: Becoming a Python Expert (Part 4)

Loop Structures

Today, let’s talk about loop structures in Python. When writing programs, we may encounter scenarios where we need to repeatedly execute a certain instruction or set of instructions. For example, if your girlfriend asks you to output “I love you” on the screen every second for an hour, how would you do it? Instead of writing the output 3600 times, you can use the following code to accomplish this task.

Rebirth: Becoming a Python Expert (Part 4)

Tip: The built-in sleep function of Python’s time module can make the program sleep. The parameter 1 indicates the number of seconds to sleep, which can be an int or float type, for example, 0.05 means 50 milliseconds.

A loop structure is a construct in a program that controls the repeated execution of a certain instruction or set of instructions. With such a structure, the previous code does not need to be written 3600 times; instead, it can be written once and placed in a loop structure to repeat 3600 times. In Python, there are two ways to construct loop structures: the for-in loop and the while loop.

For-in Loop

If you know the number of times the loop will execute, it is recommended to use a for-in loop. For example, to repeat “I love you” 3600 times, we can use the following code. Note that the code block controlled by the for-in loop is also constructed usingindentation, which is the same as how code blocks are constructed in branching structures. The code block controlled by the for-in loop is called theloop body, and the statements within the loop body will be executed repeatedly based on the loop’s settings.

Rebirth: Becoming a Python Expert (Part 4)

Explanation: The range(3600) in the above code creates a range from 0 to 3599. When we place this range in the for-in loop, we can use the loop variable i to sequentially take integers from 0 to 3599, which will cause the statements in the for-in code block to repeat 3600 times.

Supplement: Usage of the range function

range(101): generates integers from 0 to 100, noting that 101 is not included.

range(1, 101): generates integers from 1 to 100, which is a left-closed and right-open setting, i.e., [1, 101).

range(1, 101, 2): generates odd numbers from 1 to 100, where 2 is the step (stride), i.e., the value incremented each time, and 101 is not included.

range(100, 0, -2): generates even numbers from 100 to 1, where -2 is the step (stride), i.e., the value decremented each time, and 0 is not included.

You may have noticed that the output and sleep operations in the above code do not use the loop variable i. For for-in loops where the loop variable is not needed, it is customary in Python to name the loop variable as _, and the modified code is as follows. Although the result does not change, this way of writing makes you appear more professional.

Rebirth: Becoming a Python Expert (Part 4)

Let’s take another example, writing code to sum even numbers from 1 to 100.

Rebirth: Becoming a Python Expert (Part 4)

Tip: In the for-in loop, we used a branching structure to check if the loop variable i is even. The variable total is used to store the accumulated result. The print(total) statement is not indented, so it is not controlled by the for-in loop and will not be executed repeatedly.

Students can think of other methods to calculate the sum.

We can also modify the parameters of the range function, changing the starting value and stride to 2, to implement the sum of even numbers from 1 to 100 with simpler code.

Rebirth: Becoming a Python Expert (Part 4)

The built-in sum function in Python can be used to calculate the sum, thus eliminating the need for a loop structure.

Rebirth: Becoming a Python Expert (Part 4)

While Loop

If you want to construct a loop structure but cannot determine the number of repetitions, it is recommended to use a while loop. The while loop controls the loop through a boolean value or an expression that can produce a boolean value. When the value of the boolean or expression is True, the statements in the loop body (the code block with the same indentation below the while statement) will be executed repeatedly. When the value of the expression is False, the loop ends.

Using a while loop to sum integers from 1 to 100

Rebirth: Becoming a Python Expert (Part 4)

Compared to the for-in loop, in the above code, we added a variable i before the loop starts. We use this variable to control the loop, so the condition i <= 100 is given after while. In the while loop body, in addition to performing the accumulation, we also need to increment the value of variable i, so we add the statement i += 1, which will make the value of i take on 1, 2, 3, …, up to 101. When i becomes 101, the while loop condition is no longer satisfied, and the code will exit the while loop. At this point, we output the value of variable total, which is the result of summing from 1 to 100, 5050.

So how do we write the sum of even numbers from 1 to 100? Students can think about it.

Rebirth: Becoming a Python Expert (Part 4)

Let’s see if it matches what the students thought.

Break and Continue

What happens if we set the condition of the while loop to True, making the condition always true? Let’s look at the following code, still using while to construct a loop structure to calculate the sum of even numbers from 1 to 100.

Rebirth: Becoming a Python Expert (Part 4)

In the above code, using while True creates a loop with a condition that is always true, which means that if no special handling is done, the loop will never end. This is what we commonly refer to as an “infinite loop”.

To stop the loop when the value of i exceeds 100, we use thebreak keyword, which serves to terminate the execution of the loop structure. It is important to note that break only terminates the loop in which it is located, which is something to be aware of when using nested loop structures.

In addition to break, there is another keyword that can be used in loop structures,continue, which can be used to skip the subsequent code of the current loop and directly let the loop enter the next iteration, as shown in the code below.

Rebirth: Becoming a Python Expert (Part 4)

Tip: The continue keyword skips the case where i is odd, so that total += i will only be executed when i is even.

Nested Loop Structures

Students can think about whether loop structures can be nested like branching structures.

Of course, they can, meaning that a loop structure can contain another loop structure. The following example demonstrates how to output a multiplication table using nested loops.

Rebirth: Becoming a Python Expert (Part 4)Rebirth: Becoming a Python Expert (Part 4)

In the above code, the loop body of the for-in loop contains another for-in loop. The outer loop controls the generation of i rows of output, while the inner loop controls the output of j columns in one row. Clearly, the output of the inner for-in loop is a complete row in the multiplication table. Therefore, when the inner loop completes, we use a print() to achieve the effect of line breaks, allowing the subsequent output to start on a new line.

Applications of Loop Structures

Example: Number Guessing Game

Requirement: The computer generates a random number between 1 and 100. The player inputs their guessed number, and the computer provides corresponding hints such as “higher”, “lower”, or “correct”. If the player guesses the number correctly, the computer informs the user how many attempts were made, and the game ends; otherwise, the game continues.

Rebirth: Becoming a Python Expert (Part 4)

Tip: The above code uses import random to import the random module from the Python standard library, and the randrange function helps us generate a random number in the range of 1 to 100 (excluding 100). The variable counter is used to record the number of loop executions, which is the total number of guesses made by the user, and the value of counter increases by 1 with each loop.

Summary

After mastering the branching and loop structures in Python, we can solve many practical application problems. Through this lesson, students should have clarified that loop structures can be constructed using the for and while keywords. Among them,if the number of repetitions of the loop structure is known in advance, a for loop is usually used; if the number of repetitions of the loop structure cannot be determined in advance, a while loop can be used. Additionally, within loop structures, the break keyword can be used to terminate loop execution, and the continue keyword can be used to directly enter the next iteration of execution.

Leave a Comment