This is the 18th day of my participation in Gwen Challenge

The most common use of else in Python is in judgment statements, but it can also be used in loop statements and exception handling. Here’s a summary of the use of else:

Common use

statement

This is the most common use, when the condition in the if statement is not met, the code in the else statement is executed.

a = False
if a:
    print("A true")
else:
    print("A false")
Copy the code

Rare usage

Looping statements

If the else clause comes immediately after the loop statement, the else clause is executed in two cases:

When the loop body does not execute a break, the loop body terminates normally

print("Two input opportunities")
for i in range(2):
    num = int(input(Please enter a number:))
    if 10 == num:
        print("10 == num, trigger break, do not execute else clause")
        break
else:
    print("Body of loop does not execute break, else clause.")
print("End of program")
Copy the code

Execute code: When break is triggered, the else clause is not executed:

Please enter a number: 1 please enter a number: 10 10 == num, trigger break, do not execute the else clause endCopy the code

Execute the else clause when break is not triggered:

Two input opportunities please enter a number: 2 Please enter a number: 3 The loop body does not execute a break statement, execute the else clause to endCopy the code

The immediately followed else clause is also executed when the body of the while loop does not execute at all

while False:
    pass
else:
    print("If the loop body doesn't execute, I'll execute.")
Output after execution:
If the loop body does not execute, I will execute
Copy the code

Exception handling

An ELSE clause immediately following the exception handling code is executed when no exception occurs

num1 = int(input("Enter an integer:"))
num2 = int(input("Enter another integer:"))
print(The '-'*20)
try:
    print("{} / {} =".format(num1,num2),num1//num2)
except ZeroDivisionError:
    print("Invalid input, ZeroDivisionError")
else:
    print("Input legal")
print("End of program")
Copy the code

Code execution: When no exception occurs:

Input an integer: 2 input another integer: 1 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2/1 = 2 input end of legal proceduresCopy the code

When an exception occurs:

Input an integer: 2 input another integer: 0 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- input is illegal, ZeroDivisionError program endedCopy the code

conclusion

Else clause trigger condition:

  1. In a judgment statement, else clause code is executed when an if statement condition is not met
  2. In a loop statement, when the body of the loop does not execute or the body of the loop executes a break statement
  3. In exception handling, the else clause is executed when no exception occurs