The introduction of

This article introduces the loop structure of process control. Cycle structure is the repeated execution of some code, as a worker, cook, every day to knock on the code, three meals a day is repeated execution of some action, so the program must have the corresponding mechanism to control the computer has the ability to cycle execution of some action. There are two types of loop structures in Python, while loops and for loops.

The while loop

A while loop, also known as a conditional loop, means that a certain condition can be met to execute a piece of code over and over again. The syntax is as follows:

whileCondition: code1code2code3
1. If the condition after while is True, execute code 1, code 2, code 3, and code 2. If the condition is True, repeat code 1, code 2, and code 3 ".
Copy the code

Let’s illustrate the use of the while loop with a concrete example.

The basic logic of the user login program is to accept the user name and password entered by the user and then compare them with the user name and password stored in the program. If they are the same, the login succeeds. If they are different, the account or password is wrong

username = "Python"
password = "123"

name =  input("Please enter user name:")
pwd =  input("Please enter your password:")
if name == username and pwd == password:
    print("Successful landing.")
else:
    print("Wrong username or password!")
Copy the code

Usually in the login of some websites, if the authentication failure will let the user re-enter the user name and password for verification, if there are three opportunities, essentially is the above code to run three times, although you can copy the above code three times, but if the requirement has 100 opportunities? Is it going to be copied 100 times? In this case, a while loop can be used to solve the problem of repeated execution.

username = "Python"
password = "123"
count = 0  # log the number of incorrect logins

while count < 3:
    name =  input("Please enter user name:")
	pwd =  input("Please enter your password:")
	if name == username and pwd == password:
    	print("Successful landing.")
	else:
    	print("Wrong username or password!")
        count += 1  # count + 1 after failure
Copy the code

There is a problem with the above code. Although the code is simplified, how do you end a loop if the user cannot end the loop after entering the correct username and password the first or second time, which is obviously not allowed in a real business scenario? We need to use break, while+break.

username = "Python"
password = "123"
count = 0  # log the number of incorrect logins

while count < 3:
    name =  input("Please enter user name:")
	pwd =  input("Please enter your password:")
	if name == username and pwd == password:
    	print("Successful landing.")
        break  End this layer loop after successful login
	else:
    	print("Wrong username or password!")
        count += 1  # count + 1 after failure
Copy the code

A loop can be terminated with a break. If a while loop has multiple nested levels, exiting each loop requires a break at each level.

username = "Python"
password = "123"
count = 0  # log the number of incorrect logins

while count < 3:  # first layer loop
    name =  input("Please enter user name:")
	pwd =  input("Please enter your password:")
	if name == username and pwd == password:
    	print("Successful landing.")
        while True:  # second loop
            cmd = input('Please enter the command you want to execute :')
            if cmd == 'quit':
                break  This is used to end the layer 2 loop
            else:
                print(f'{cmd}Command running ')
        break  # used to end the layer loop, i.e. the first layer loop
	else:
    	print("Wrong username or password!")
        count += 1  # count + 1 after failure
Copy the code

The use of while+break is used to terminate the loop, while continue is used to terminate the loop and proceed to the next loop.

Print all numbers between 1 and 10 except 5
num = 0
while num < 10:
    num += 1
    if num == 5:
        continue  If the loop continues, the code will not run and will go directly to the next loop
    print(num)
Copy the code

The end of the while loop can also be used with else. When the while loop completes normally and is not interrupted by a break, the statement following the else is executed, that is, while+else.

num = 0
while num < 5:
    print(num)
    num += 1
else:
    print('Loop ends normally')   # will be executed
print('----- exits the while loop properly -------')

# if the execution is broken, the else statement is not executed
num = 0
while num < 5:
    print(num)
    if num == 2:
        break
    num += 1
else:
    print('Loop ends normally')  # will not be executed
print('-----break exits while loop -------')
Copy the code

The for loop

The second implementation of the loop structure is that, in theory, the for loop can do anything the while loop can do. The reason for using the for loop is that it is cleaner to use than the while loop when iterating over values.

The syntax for the for loop is as follows:

forThe variable nameinIterable:Iterables include lists, dictionaries, and strings. We will cover iterables latercode1code2
Copy the code

For example, we use the for loop to iterate over (fetching every element in the iterable) a list of list1 = [1, 2, 3]

for i in list1:
    print(i)
# The result is as follows
1
2
3
Copy the code

Take a look at the steps of the for loop

1.Read the first value from list1 and assign it to I (I =1), and then executes the loop body code2.Read the second value from list1 and assign it to I (I =2), and then executes the loop body code3.Repeat the process until the list has been readCopy the code

The for loop can also be nested

Print the following graphic with a nested for loop* * * * * * * * * * * *for i in range(3) :# range(3) produces the numbers 0 to 2, representing 3 rows
    for i in range(4) :# range(4 produces 0 to 3 * in each row)
        print(The '*', end=' ')  # end='' means no line breaks
    print(a)# print() indicates a newline
Copy the code

The login function can also be implemented using the for loop, so the break continue else can also be used in the for loop. The syntax is the same as that of the while loop.

username = "Python"
password = "123"

for i in range(3) :# means three chances
    name =  input("Please enter user name:")
	pwd =  input("Please enter your password:")
	if name == username and pwd == password:
    	print("Successful landing.")
        break
     else:
        print('Try it again')
else:
    print('For loop completes properly')
Copy the code

Practice — Output the multiplication table

Implement the multiplication table using the while loop and the for loop respectively

# the while loop
i = 1  Line # said
while i <= 9:
    j = 1  # j denotes the column
    while j <= i:
        print(f'{j} * {i} = {i*j}', end=' ')
        j += 1
    else:
        print()
    i += 1
    
# for loop
for i in range(1.10) :for j in range(1, i+1) :print(f'{j} * {i} = {j*i}', end=' ')
    print(a)Copy the code

At the end of the article

If you think my writing is good, please scan the QR code below to follow my wechat official account for more Python knowledge