Basic questions for python newbies about the nesting of while loops
PHP中文网
PHP中文网 2017-05-24 11:35:20
0
2
733

The source code is as follows:

# -*- coding:gb2312 -*-
#站起来,坐下,站起来,转5个圈,坐下。整个流程执行10次
Process1 = 1
Process2 = 1
while Process1 < 10: # 这个Process1 代表外面大的while循环
    print("="*5)
    print("第%d次执行"%Process1)
    print("站起来")
    print("坐下")
    print("站起来")
    while Process2 <= 5: # 这个Process2 代表嵌套在里面的while小循环
        print("转%d个圈"%Process2)
        Process2 = Process2 + 1
    print("坐下")
    Process1 = Process1 + 1

Results of the:

My question is:
Why is the part marked in red in the picture, that is, the inner loop of Process2, only executed once in the entire process, instead of following the entire process outside? Execute the big loop 10 times? How can I improve it so that it can continue to be nested in the entire program?

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
刘奇

After executing the first outer loop, the initialization of Process2 的值变成了 6, 在执行第二次外循环及以后时,它的值一直是 6, 所以内循环不执行.
如果你想让它执行, Process2 should be placed inside the outer loop.

Process1 = 1
while Process1 < 10: # 这个Process1 代表外面大的while循环
    print("="*5)
    print("第%d次执行"%Process1)
    print("站起来")
    print("坐下")
    print("站起来")
    Process2 = 1
    while Process2 <= 5: # 这个Process2 代表嵌套在里面的while小循环
        print("转%d个圈"%Process2)
        Process2 = Process2 + 1
    print("坐下")
    Process1 = Process1 + 1
给我你的怀抱

The variable assignment of the inner loop must be placed inside the outer loop. It is guaranteed that the inner loop variables start from 1 every time the outer loop is executed. Otherwise, the inner loop variable becomes 6 after the first run, and remains 6 thereafter, resulting in no further execution.

# -*- coding:gb2312 -*-
#站起来,坐下,站起来,转5个圈,坐下。整个流程执行10次
Process1 = 1
while Process1 < 10: # 这个Process1 代表外面大的while循环
    print("="*5)
    print("第%d次执行"%Process1)
    print("站起来")
    print("坐下")
    print("站起来")
    Process2 = 1
    while Process2 <= 5: # 这个Process2 代表嵌套在里面的while小循环
        print("转%d个圈"%Process2)
        Process2 = Process2 + 1
    print("坐下")
    Process1 = Process1 + 1
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template