How to use Python flow Control statement
This article mainly introduces the relevant knowledge of how to use Python process control statements, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this Python process control statement. Let's take a look at it.
There are two kinds of loop mechanisms in Python: while and for, in which while loop is a conditional cycle.
While loop while conditional statement: / / if the condition is true, execute the following method functionsWhenConditionTrue ()
An example of a simple for loop:
Count = 0while count < 3: print (count) count + = 1
The results are obtained:
0
one
two
Endless cycle and efficiency problem
If the conditional judgment is always true, it will go on forever, forming an endless cycle.
Count = 0while True: print (count) count + = 0 how to end the loop
Here we take the login of the system as an example to introduce the way to end the loop.
Method one changes the condition to False, and the abbreviation of username = "Vooce" pwd = "666" / / password: flag = Truewhile flag: inp_name = input ("Please enter your user name:") inp_pwd = input ("Please enter your password:") if inp_name = = username and inp_pwd = = pwd: print ("Login successful!") Flag = False # the code here will also run until you enter the next while loop judgment condition, else: print ("wrong username or password, please re-enter!") Print ("logging in to the system...") Method 2: break, immediately terminate the abbreviation of username = "Vooce" pwd = "666" / / password while True: inp_name = input ("Please enter your user name:") inp_pwd = input ("Please enter your password:") if inp_name = = username and inp_pwd = = pwd: print ("login succeeded!") Break # exit this layer loop immediately # the code here will not run else: print ("wrong username or password, please re-enter!") Print ("logging in to the system...") Loop nesting and exit of while
If you want to use while, method one: you can exit all the loops directly:
Flag = Truewhile flag: while flag: while flag: flag = False
Method 2: if you use break, each layer should be equipped with a break
While True: # layer 1 while True: # layer 2 while True: # layer 3 break # exit layer 3 break # exit layer 2 break # exit layer 1 article on "how to use Python flow control statements" ends here, thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use Python process control statements". If you want to learn more knowledge, you are welcome to follow the industry information channel.