1.for
How to use regular for
for i in range(3): print(i)for is used with else
_user = "123456" _password = "123456" for i in range(3): user = input("Please enter user name: ") password = input("Please enter your password: ") if user == _user and password == _password: print("Welcome to login!") break else : print("Incorrect input! There is ",2-i,"a second chance!") else: # else matching for print("The system is locked!")This is a simple login procedure, which loops 3 times in total. If the input is correct, it will jump out of the loop. If the input is wrong, the next loop will be executed. If the input is wrong three times, the program will end, and the user will be prompted that "the system has been locked".
When the input jumps out correctly, the else matching for is not executed, and the code after the else statement is executed after the input error three times
According to this simple procedure, it can be concluded that:
1. When the for loop is executed without jumping out, execute the statement after the else
2. When the for loop jumps out, the statement after the else is not executed.
2.while
General usage of while statement
i = 0 while i < 3: print(i) i += 1
The usage of while statement with else
_user = "123456" _password = "123456" i = 0 while i < 3: user = input("Please enter user name: ") password = input("Please enter your password: ") if user == _user and password == _password: print("Welcome to login!") break else : print("Incorrect input! There is ",2-i,"a second chance!") i += 1 else: # else matching for print("The system is locked!")The else of the while statement has the same effect as the else of the for statement:
If an interruption occurs in the loop, the else statement is not executed; if there is no interruption after the execution is completed, the else statement is executed