Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python loop structure

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use Python loop structure". In daily operation, I believe many people have doubts about how to use Python loop structure. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use Python loop structure". Next, please follow the editor to study!

Application scenario

When we write a program, we are bound to encounter situations where one or some instructions need to be executed repeatedly. For example, using a program to control the robot to play football, if the robot holds the ball and has not yet entered the shooting range, then we have to always issue instructions to make the robot move towards the goal. In this scene, moving the robot toward the goal is a repetitive action, and of course, the branch structure described in the previous lesson will be used to determine whether the robot holds the ball and whether it is in the shooting range. To take another simple example, if we want to print "hello, world" on the screen every second and continue to print for an hour, we certainly can't directly write the print ('hello, world') code 3600 times. We also need a loop structure here.

A loop structure is a structure in a program that controls the repeated execution of one or some instructions. There are two ways to construct a loop structure in Python, one is the for-in loop, the other is the while loop.

For-in cycle

If you know exactly how many times the loop is executed, we recommend using a for-in loop, such as calculating the sum of 1 to 100. The block of statements controlled by the for-in loop is also determined by indentation, which is exactly the same as the branch structure, as you can see in the following code.

"total = 0for x in range (1101): total + = xprint (total)"total = 0for x in range (1101): total + = xprint (total)"

It is important to note that range (1,101) in the above code can be used to construct a range from 1 to 100. when we put such a range into a for-in loop, we can fetch integers from 1 to 100 in turn through the previous loop variable x. Of course, the use of range is very flexible, and here is an example:

Range (101): can be used to generate integers in the range of 0 to 100, but it is important to note that it is less than 101.

Range (1,101): can be used to produce integers in the range of 1 to 100, which is equivalent to an open interval followed by a closed interval.

Range (1,101,2): can be used to generate odd numbers from 1 to 100, where 2 is the step size, that is, the value incremented each time.

Range (100,0,-2): can be used to produce even numbers from 100 to 1, where-2 is the step size, the value of each decreasing number.

Knowing this, we can use the following code to achieve the sum of even numbers between 1 and 100.

"total = 0for x in range (2,101,2): total + = xprint (total) while cycle by using for cycle to realize the sum of even numbers between 1to 100 Version: 0.1Author: Luo Hao"

If you want to construct a loop structure that does not know the specific number of loops, we recommend using while loops. The while loop controls the loop through an expression that produces or converts a Bool value. The expression's value of True continues the loop; the expression's value of False ends the loop.

Let's take a look at how to use the while loop through a "guessing" Mini Game. The rules of the number guessing game are: the computer gives a random number between 1 and 100, the player enters the number he guesses, and the computer gives the corresponding prompt information (bigger, smaller, or guessed right). If the player guesses the number, the computer prompts the user to guess a total of how many times, the game is over, otherwise the game continues.

"" guessing game Version: 0.1Author: Luo Hao "" import random# produces a random number in the range of 1-100 answer = random.randint (1,100) counter = 0while True: counter + = 1 number = int (input ('please enter:') if number

< answer: print('大一点') elif number >

Answer: print ('smaller') else: print ('Congratulations on your guess!') Break# shows how many times the user guessed print (f 'you guessed {counter}) break and continue when exiting the while loop.

The above code uses while True to construct a loop with constant conditions, which means that the loop will not end without special treatment, which is often referred to as a "dead loop." In order to exit the loop structure when the user guesses a number, we use the break keyword, which ends the loop early. It is important to note that break can only terminate the loop it is in, which needs to be noted when using a nested loop structure, which we will talk about in the following example. In addition to break, another keyword is continue, which can be used to abandon the subsequent code of this loop and allow the loop to move on to the next round.

Nested loop structure

Like branch structures, loop structures can be nested, that is, loop structures can also be constructed in the loop. The following example demonstrates how to output a multiplication table (ninety-nine table) through a nested loop.

"" print multiplication table Version: 0.1Author: Luo Hao "" for i in range (1,10): for j in range (1, I + 1): print (f'{I} * {j} = {I * j}', end='\ t') print ()

Obviously, in the above code, the outer loop is used to control the output of a total of nine lines, while the inner loop is used to control how many columns are output for each row. The output in the inner loop is all the columns in the ninety-nine table row, so when the inner loop is complete, there is a print () to achieve the effect of newline output.

Example of a loop: enter a positive integer to determine whether it is a prime or not.

Tip: a prime is an integer greater than 1 that is divisible only by 1 and itself.

"" enter a positive integer to determine whether it is a prime Version: 0.1Author: Luo Hao "" num = int (input ('please enter a positive integer:') end = int (num * * 0.5) is_prime = Truefor x in range (2 End + 1): if num% x = 0: is_prime = False breakif is_prime and num! = 1: print (f'{num} is prime') else: print (f'{num} is not prime') example 2: enter two positive integers Calculate their maximum common divisor and least common multiple.

Hint: the greatest common divisor of two numbers is the largest of the common divisors of two numbers; the least common multiple of two numbers is the smallest number that can be divisible by two numbers at the same time.

Enter two positive integers to calculate their maximum common divisor and least common multiple Version: 0.1Author: Luo Hao "" x = int (input ('x =')) y = int (input ('y =')) if x > y: X, y = y, x # Python can exchange the values of two variables for factor in range (x, 0) in this way -1): if x% factor = 0 and y% factor = 0: print (the maximum common divisor of f'{x} and {y} is {factor}') print (the least common multiple of f'{x} and {y} is {x * y / / factor}') break so far The study on "how to use the Python loop structure" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report