Python - break, continue, return, exit, pass differences - advanced path

1, Distinction

Serial numbernamedescribeuse
1breakIt is used to terminate the loop statement, that is, if the loop condition has no False condition or the sequence has not been completely recursive, the execution of the loop statement will also be stopped.Used in while and for loops, if you use nested loops, the break statement stops executing the deepest loop and starts executing the next line of code.
2returnEnd function, return parametersWhen the program runs to the first return encountered, it returns (exit the def block) and will not run the second return.
3continueSkip the remaining statements of the current loop and proceed to the next loopThe continue statement is used in while and for loops.
4exit(num)Exit the entire cycleParameters that can be omitted. Normally, 0 indicates that the program exits normally, and 1 indicates that the program exits due to an error. In practice, any integer data can be used to represent different user-defined error types.
5passNothing is done to maintain the integrity of the program structureUsually do placeholder statements

2, Instance

1,break

It is used to terminate the loop statement, that is, if the loop condition has no False condition or the sequence has not been completely recursive, the execution of the loop statement will also be stopped.

[1] break in for loop

for i in range(1, 11):
    if i % 2 == 0:
        break
    # Stop when the first condition is met. Do not output qualified statements and stop.
    print("i = ", i)

Output results:

i =  1

[2] break in while loop

var = 1
while var == 1:  # The expression is always true
    num = int(input("Guess a number within 10:"))
    if num == 5:
        print("You guessed right")
        break
    print("Wrong guess. Go on...")

print("Good bye!")

Output results:

Guess a number within 10: 6
 Wrong guess. Go on...
Guess a number within 10: 5
 You guessed right
Good bye!

[3] break in nested loop

for i in range(2):
    print("i = ", i)
    for j in range(2, 5):
        if j == 3:
            print("Exit second for loop")
            break
        print("j = ", j)

Output results:

i =  0
j =  2
 Exit second for loop
i =  1
j =  2
 Exit second for loop

In the for loop, if you use nested loops, the break statement stops executing the deepest loop and starts executing the next line of code.

2,return

[1] No statement after return

def test():
    a = 2
    return a

print(test())

Output results:

2

[2] return is followed by a statement. Will it be executed?

def test():
    a = 2
    return a
    s = 3
    print(s)

print(test())

Output results:

2

When the program runs to the first return encountered, it returns (exit the def block) and will not run the statement after return.

[3] return and finally are used together. What will be the result?

def test(s):
    try:
        if s == 'python Big star':
            print('It's him, it's him, it's him')
        return True
    except:
        print("System failure!")
        return False
    finally:
        print("follow python Big star, you deserve it!")


print(test("python Big star"))

Output results:

It's him, it's him, it's him
 follow python Big star, you deserve it!
True

Because there is no exception, the return statement in the try block will be executed, but finally must be executed, so the finally statement is executed before executing the return in the try

3,continue

[1] Single cycle

for i in range(6):
    if i == 0:
        continue
    print(i)

Output results:

1
2
3
4
5

When i == 0, 0 is not printed, but the for loop continues

[2] Nested loop

for i in range(2):
    print("i = ", i)
    for j in range(2, 5):
        if j == 3:
            print("Continue with the second for loop")
            continue
        print("j = ", j)

Output results:

i =  0
j =  2
 Continue with the second for loop
j =  4
i =  1
j =  2
 Continue with the second for loop
j =  4

break is to end the whole loop body, while continue is to end this loop and continue the loop.

4,exit(num)

Call the exit() function to terminate the Python program. num is an omitted parameter. Normally, 0 indicates that the program exits normally, and 1 indicates that the program exits due to an error. In practice, any integer data can be used to represent different user-defined error types.

[1] Use exit in single layer loops

for i in range(6):
    if i == 0:
        exit(101)
    print(i)

Output results:

0
1
2

Process finished with exit code 101

[2] Use exit in nested loops

for i in range(2):
    print("i = ", i)
    for j in range(2, 5):
        if j == 3:
            print("error")
            exit(102)
        print("j = ", j)

Output results:

i =  0
j =  2
error

Process finished with exit code 102

No matter where the exit function appears in the program, as soon as the program is invoked to the exit () function during execution, the program terminates operation immediately. The exit() function is often used to exit, end, or debug code when a program error occurs.

5,pass

pass does nothing. It is generally used as a placeholder statement.

[1] Use in a for loop

for i in range(1, 7):
    if i % 2 == 0:
        pass
    # pass does nothing
    print(i)

Output results:

1
2
3
4
5
6

Process finished with exit code 0

[2] Use in functions

def fn(n):
    pass

The pass here occupies a position, because if you define an empty function, the program will report an error. When you don't think about the content of the function, you can fill it with pass to make the program run normally.

Keywords: Python Pycharm

Added by little_tris on Thu, 07 Oct 2021 19:09:02 +0300