Detailed Explanation of Application Scenario of Python Loop Structure

  • 2021-07-13 05:56:17
  • OfStack

Preface

If we need to execute one or some instructions repeatedly in the program, such as using the program to control the robot to play football, if the robot holds the ball and has not yet entered the shooting range, then we need to issue the instructions to let the robot run towards the goal. Of course, you may have noticed that there are not only actions that need to be repeated in the description just now, but also the branch structure that we talked about in the previous chapter.

Let's give another simple example. For example, in our program, if we want to print a string like "hello, world" on the screen every 1 second for 1 hour, we definitely can't write the code print ('hello, world') 3600 times. If we really need to do this, the programming work will be too boring. Therefore, we need to understand the loop structure under 1. With the loop structure, we can easily control the repetition, repetition and repetition of something or something.

There are two ways to construct the cyclic structure in Python, one is for-in cycle, and the other is while cycle.

for-in cycle

If you know exactly how many times the loop is executed or if you want to iterate over a container (which will be covered later), we recommend using the for-in loop, such as $\ sum_ {n=1} ^ {100} n $calculated in the following code.


"""
 Use for Loop implementation 1~100 Summation 

Version: 0.1
Author:  Tang Tang 
"""

sum = 0
for x in range(101):
  sum += x
print(sum)

It should be noted that the range type in the above code, range can be used to generate a constant numeric sequence, and this sequence is usually used in loops, for example:

range (101) can produce a sequence of integers from 0 to 100. range (1,100) can produce a sequence of integers from 1 to 99. range (1, 100, 2) can produce an odd sequence from 1 to 99, where 2 is the step size, that is, the increment of the numerical sequence.

Knowing this point, we can use the following code to achieve even summation between 1 and 100.


"""
 Use for Loop implementation 1~100 Sum even numbers between 

Version: 0.1
Author:  Tang Tang 
"""

sum = 0
for x in range(2, 101, 2):
  sum += x
print(sum)

You can also do the same by using a branch structure in a loop, as shown below.


"""
 Use for Loop implementation 1~100 Sum even numbers between 

Version: 0.1
Author:  Tang Tang 
"""

sum = 0
for x in range(1, 101):
  if x % 2 == 0:
    sum += x
print(sum)

while cycle

If we want to construct a loop structure without knowing the specific number of loops, we recommend using while loop. while loop controls the loop through an expression that can generate or convert bool value. The value of the expression is True loop continues and the value of the expression is False loop ends.

Let's take a look at how to use while loop through a small game of "guessing numbers" (the computer produces a random number between 1 and 100, people input their guessed numbers, and the computer gives corresponding prompt information until people guess the numbers produced by the computer).


"""
 Guess numbers game 
 Computer output 1 A 1~100 The random number between them is guessed by people 
 The computer gives prompts according to the numbers guessed by people 1 Point / Small 1 Point / Guess right 

Version: 0.1
Author:  Tang Tang 
"""

import random

answer = random.randint(1, 100)
counter = 0
while True:
  counter += 1
  number = int(input(' Please enter : '))
  if number < answer:
    print(' Big 1 Point ')
  elif number > answer:
    print(' Small 1 Point ')
  else:
    print(' Congratulations on your guess !')
    break
print(' You guessed in total %d Times ' % counter)
if counter > 7:
  print(' Your IQ balance is obviously insufficient ')

Note: The above code uses the break keyword to terminate the loop in advance. It should be noted that break can only terminate the loop in which it is located. This 1 point needs attention when using nested loop structure (which will be discussed below). In addition to break, another keyword is continue, which can be used to abandon the subsequent code of this loop and directly let the loop enter the next round.

Like branch structure 1, loop structure can also be nested, that is to say, loop structure can also be constructed in loop. The following example demonstrates how to output a 99 multiplication table through a nested loop.


"""
 Output multiplication formula table (99 Table )

Version: 0.1
Author:  Tang Tang 
"""

for i in range(1, 10):
  for j in range(1, i + 1):
    print('%d*%d=%d' % (i, j, i * j), end='\t')
  print()

Exercise

Exercise 1: Enter a number to judge whether it is a prime number.


"""
 Input 1 A positive integer to judge whether it is a prime number 

Version: 0.1
Author:  Tang Tang 
Date: 2018-03-01
"""
from math import sqrt

num = int(input(' Please enter 1 Positive integers : '))
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 a prime number ' % num)
else:
  print('%d Is not a prime number ' % num)

Exercise 2: Enter two positive integers and calculate the greatest common divisor and the least common multiple.


"""
 Enter two positive integers to calculate the greatest common divisor and the least common multiple 

Version: 0.1
Author:  Tang Tang 
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('%d And %d The greatest common divisor of is %d' % (x, y, factor))
    print('%d And %d The least common multiple of is %d' % (x, y, x * y // factor))
    break

Exercise 3: Print a triangular pattern.


"""
 Print various 3 Angle pattern 

*
**
***
****
*****

  *
  **
 ***
 ****
*****

  *
  ***
 *****
 *******
*********

Version: 0.1
Author:  Tang Tang 
"""

row = int(input(' Please enter the number of rows : '))
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()

Related articles: