您的位置:首頁技術文章
文章詳情頁

python小白的基礎問題 關于while循環的嵌套

瀏覽:111日期:2022-06-30 10:56:01

問題描述

源代碼如下:

# -*- coding:gb2312 -*-#站起來,坐下,站起來,轉5個圈,坐下。整個流程執行10次Process1 = 1Process2 = 1while 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

執行結果:python小白的基礎問題  關于while循環的嵌套

我的問題是:為什么如圖紅色標記的這一部分,也就是Process2這一部分的內循環,在整個過程只執行了一次,而不是隨著外面的整個大循環執行10次? 我如何改進才可以讓他隨著整個程序一直嵌套在里面循環下去?

問題解答

回答1:

執行第一次外循環之后, Process2 的值變成了 6, 在執行第二次外循環及以后時,它的值一直是 6, 所以內循環不執行. 如果你想讓它執行, Process2的初始化應該放到外循環里面.

Process1 = 1while 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回答2:

要把內層循環的變量賦值放在外層循環里面才行。保證在每次外層循環時,內層循環變量都從1開始。不然,內層循環變量第一次運行后變成6,之后一直是6,導致后面不再執行。

# -*- coding:gb2312 -*-#站起來,坐下,站起來,轉5個圈,坐下。整個流程執行10次Process1 = 1while 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

標簽: Python 編程
相關文章:
国产综合久久一区二区三区