Python while infinite loop

do not understand why this function does not write break will loop infinitely, ask for help
def diedai (size):

size=size+1
print("size=",size)
while (size<=2):
    print("size=",size)
    diedai(size)
    -sharpbreak

diedai (1)

clipboard.png

Jun.16,2022

because the size of while is always equal to 2 when it is called for the first time, and it never comes out which is equivalent to

.
def diedai(size):

    size=size+1
    print("size=",size)
    while (size<=2):
        print("size=",2)
        diedai(2)

diedai(1)

diedai (2) only PP and then print

so it is equivalent to executing this code

size = 2
print("size=", size)
while (size <= 2):
    print("size=", size)
    print("size=", size + 1)

original code:

def diedai(size):
    size = size + 1
    print("size=", size)
    
    while (size<=2):
        print("size=", size)  -sharp a
        diedai(size)  -sharp b
        -sharp break
        
    print("diedai , size=", size)
    
diedai(1)
The

upstairs is quite right. When you first call the detail () function, the function enters the while loop and does not pop up, because the size you pass in step b only determines whether the next call to the diedai () function will enter the while loop, but will not really change the value of size
. First of all, you should know that this function logic is similar to recursive function
the front part of the execution result

.
size= 2
size= 2  -sharp ""
size= 3
diedai , size= 3
size= 2
size= 3
diedai , size= 3
size= 2
size= 3
diedai , size= 3
size= 2
size= 3
diedai , size= 3
...

from the first "in loop" to the next "diedai function end", it is a while loop. The order of execution of this loop is a b a b a. The whole function has been executing these two lines of code.

if you change while to if , the function becomes a recursive function, and when the condition is not satisfied, it will jump out of the recursive function layer by layer

.

because when this program executes to the diedai (2) function. The size in this function is always 2, so it won't stop. The landlord may think that size is changed to 3 when iterating to the diedai (3) function, but in fact the variables in the iterated function have nothing to do with the upper level. That is to say, the size in diedai (3) has nothing to do with size in diedai (2)


size is a local variable, the diedai execution loop in while executes once and ends because of internal size=3, but the external size is always 2, the while loop will not be interrupted, and size will only be interrupted if it is global.

Menu