Application Scenarios for Loop Structures
If we need to repeat an instruction or instructions in a program, such as a program to control a robot playing soccer, then if the robot is holding the ball and is not yet in range of the goal, then we need to keep issuing instructions for the robot to run toward the goal. Of course, as you may have noticed, it's not just the actions that need to be repeated, but also the branching structure that we talked about in the previous section. As a simple example, if we want our program to print the string "hello, world" on the screen every second for an hour, we certainly can't write the code print('hello, world') 3600 times, if we really need to do that, then programming would be too boring. Therefore, we need to know about loop structures, with which we can easily control something or the other to repeat, repeat and repeat again. There are two ways to construct a loop structure in Python, a for-in loop and a while loop.
for-in loop
If it is clear how many times the loop will be executed or if you want to iterate over a container (more on that later), then we recommend using a for-in loop, such as the following code to calculate the
expense or outlayforcyclic implementation1~100look for a draw (chess) Version: 0.1 Author: Luo Hao """ sum = 0 for x in range(101): sum += x print(sum)
It is important to note that the range type in the above code, range can be used to produce an invariant sequence of values, and this sequence is usually used in loops, for example:
- range(101) produces a sequence of integers from 0 to 100.
- range(1, 100) produces a sequence of integers from 1 to 99.
- range(1, 100, 2) produces a sequence of odd numbers from 1 to 99, where 2 is the step size, i.e. the increment of the sequence of values.
Knowing this, we can use the following code for summing even numbers between 1 and 100.
expense or outlayforcyclic implementation1~100Sum the even numbers between Version: 0.1 Author: Luo Hao """ sum = 0 for x in range(2, 101, 2): sum += x print(sum)
The same functionality can also be achieved by using a branching structure in a loop, as shown in the code below.
expense or outlayforcyclic implementation1~100Sum the even numbers between Version: 0.1 Author: Luo Hao """ sum = 0 for x in range(1, 101): if x % 2 == 0: sum += x print(sum)
while loop
If you want to construct a loop structure that does not know the exact number of loops, we recommend the use of while loops, while loops are controlled by an expression that produces or converts the value of a bool, the value of which is True to continue the loop, and the value of which is False to end the loop. The following is a small game of "Guess the Number" (the computer produces a random number between 1 and 100, the person enters the number he/she guesses, and the computer gives the corresponding hints until the person guesses the number produced by the computer) to see how to use the while loop.
guessing game Calculating a1~100Random numbers between them are guessed by people The computer gives hints based on the person's guesses for each of the numbers larger/Smaller./That's right. Version: 0.1 Author: Luo Hao """ import random answer = (1, 100) counter = 0 while True: counter += 1 number = int(input('Please enter: ')) if number < answer: print('Bigger') elif number > answer: print('Smaller') else: print('Congratulations on guessing correctly!') break print('You guessed a total of %d times' % counter) if counter > 7: print('Your IQ balance is clearly lacking')
Note: The code above uses the break keyword to terminate the loop early. Note that break can only terminate the loop it is in, which is important to keep in mind when using nested loops (discussed below). In addition to break, there is another keyword, continue, which can be used to abort the subsequent code in the loop and let the loop proceed to the next round.
Like branching structures, loops can be nested, which means that loops can also be constructed within loops. The following example demonstrates how to output a multiplication table through a nested loop.
Output multiplication table(name of "coins" radical in Chinese characters (Kangxi radical 9)) Version: 0.1 Author: Luo Hao """ for i in range(1, 10): for j in range(1, i + 1): print('%d*%d=%d' % (i, j, i * j), end='\t') print()
practice
Exercise 1: Enter a number to determine if it is prime.
Enter a positive integer to determine if it is a prime number. Version: 0.1 Author: Luo Hao Date: 2018-03-01 """ from math import sqrt num = int(input('Please enter a positive integer: ')) end = int(sqrt(num)) is_prime = True for x in range(2, end + 1): if num % x == 0: is_prime = False break if is_prime and num != 1: print('%d is prime' % num) else: print('%d is not prime' % num)
Exercise 2: Enter two positive integers and calculate the greatest common divisor and the least common multiple.
Calculate the greatest common divisor and least common multiple by entering two positive integers. Version: 0.1 Author: Luo Hao Date: 2018-03-01 """ x = int(input('x = ')) y = int(input('y = ')) if x > y: x, y = y, x for factor in range(x, 0, -1): if x % factor == 0 and y % factor == 0: print('The greatest common divisor of %d and %d is %d' % (x, y, factor)) print('The least common multiple of %d and %d is %d' % (x, y, x * y // factor)) break
Exercise 3: Print a triangle pattern.
Print various triangle patterns * ** *** **** ***** * ** *** **** ***** * *** ***** ******* ********* Version: 0.1 Author: Luo Hao """ row = int(input('Please enter the number of lines: ')) for i in range(row): for _ in range(i + 1): print('*', end='') print() for i in range(row): for j in range(row): if j < row - i - 1: print(' ', end='') else: print('*', end='') print() for i in range(row): for _ in range(row - i - 1): print(' ', end='') for _ in range(2 * i + 1): print('*', end='') print()