📖 preface

Nice code is the same, disgusting program promotion pay.

Almost every programmer knows or understands design patterns, whether or not they should, but most people are used to writing code in a quick way. No matter how much business logic is thousands of lines on a class, such development can also be reduced to three steps; Define properties, create methods, call displays, Done! It was just a cool development, reconstructing the crematorium.

Today the blogger is going to talk to you about how to use Python loops! Do not like spray, if you have suggestions welcome to supplement, discussion!

For more information on installation and sinification, see this post from the bloggerDownload and Install VsCodeAs well asPython series: windows10 to configure Python3.0 development environment!Restart VsCode after installation!


🚀 last Come on!

Loop statements in Python are for and while statements. The control structure of a Python loop is shown below:


whilecycle

The general form of the while statement in Python:

While condition: statementCopy the code

Code from the previous article

@param: @return: "a = 1 while a < 7: if(a % 2 == 0): print(a, "one") else : print(a, "two") a +=1Copy the code

Also pay attention to colons and indents. Also, there is no do.. The while loop.

Use while to calculate the sum from 1 to 100:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. N = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter counter += 1 print("1 to %d = %d" % (n,sum))Copy the code

Here are the results:

An infinite loop

You can implement an infinite loop by setting the conditional expression to never be false, as follows:

@param: @return: "" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. Num = int(input(" input :")) print (" input :", num) print (" input :") )Copy the code

Here are the results:

In the command operator you can use CTRL+C to exit the current infinite loop. In VsCode you can exit the current infinite loop by ending debugging

Infinite loops are useful for real-time requests from clients on the server.

whilerecyclingelsestatements

In a while… Else To execute the else block if the condition is false:

"@name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. @param: @return:" count = 0 while count < 9: Print (count, "< 9") else: print (count," < 9")Copy the code

Here are the results:

Simple statement set

similarifStatement syntax, if yourwhileThere is only one statement in the body of the loop, which you can associate withwhileWrite on the same line, as follows:

@param: @return: "" flag = 1 while (flag): Welcome to Chen Yongjia's blog! ') print ("Hello Welcome!" )Copy the code

Here are the results:

Note: In the above infinite loop you can use CTRL+C in the command operator to break the loop. In VsCode you can exit the current infinite loop by ending debugging


For statement

A Python for loop can iterate over any sequence of items, such as a list or a string. The general format of a for loop is as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>
Copy the code

Python loopCycle:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. ''' languages = ["C", "C++", "Perl", "Java", "Python"] for x in languages: print (x)Copy the code

Here are the results:

The for instance uses the break statement, which is used to break out of the current body of the loop:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. '' sites = ["Baidu", "Google","Mr_Chen","Taobao"] for site in sites: if site == "Runoob": print(" Chen's blog! ) break print(" loop data "+ site) else: print(" no loop data!" Print (" Complete loop!") )Copy the code

Here are the results:

range()function

If you need to traverse a sequence of numbers, you can use the built-inrange()Function. It generates a sequence like this:

@param: @return: "" for I in range(9): print(I)Copy the code

Here are the results:

You can also use range to specify a range of values:

@param: @return: "" for I in range(2,9): print(I)Copy the code

Here are the results:

Also can makerangeStart with the specified number and specify different increments (even negative numbers, sometimes called ‘steps’, how many to cross at once!). :

@param: @return: "" for I in range(2,11,4): print(I)Copy the code

Here are the results:

Negative:

@param: @return: "" for I in range(-10,-100,-5): print(I)Copy the code

Here are the results:

You can also combinerange() 和 len()Function to traverse the index of a sequence, as follows:

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. ''' a = ['Google', 'Baidu', 'Mr_Chen', 'Taobao', 'QQ'] for i in range(len(a)): print(i, a[i])Copy the code

Here are the results:

You can also userange()Function to create a list:

@param: @return: "" print(list(range(5)))Copy the code

Here are the results:


break 和 continueStatements and loopselseclause

breakStatements can jump outfor å’Œ whileCirculatory body of. If you are fromfor 或 whileLoop termination, any corresponding loopelseThe block will not execute. Here’s an example:

@param: @return: "" for letter in 'Mr_XiaoChen': If letter == 'a': break print (' a', letter) var = 10 If var == 5: break print ("Good bye!") )Copy the code

Here are the results:

The continue statement is used to tell Python to skip the remaining statements in the current loop block and proceed to the next loop.

@param: @return: "" for letter in 'Mr_XiaooChen': If letter == 'o'; if letter == 'o'; if letter = 'o'; Continue print (' current value :', var) print ("Good bye!") )Copy the code

Here are the results:

A loop statement can have an else clause, which is executed when the loop terminates due to the exhaustion of the list (in the for loop) or the condition changing to false (in the while loop), but not when the loop is terminated by a break. The following is an example of a loop to query primes:

@param: @return: "" for n in range(2, 10): For x in range(2, n): if n % x == 0: print(n, '= ', x, '*', n//x) break else:Copy the code

Here are the results:


passstatements

The Python pass is an empty statement to preserve the integrity of the program structure. Pass does not do anything and is usually used as a placeholder statement, as shown in the following example

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. @param: @return:" "while True: passCopy the code

The following instances are in letters forCWhen performingpassBlock:

@param: @return: "" for letter in 'Mr_Chen': If letter == 'C': pass print (' execute pass block ') print (' current letter :', letter) print ("Good bye!" )Copy the code

Here are the results:


Here we go :Python’s loop! Share finished, go to try it!


🎉 finally

  • For more references, see here:Chen Yongjia’s blog
  • Like the little friend of the blogger can add a concern, point a like oh, continue to update hey hey!