python小白的基礎問題 關于while循環的嵌套
問題描述
源代碼如下:
# -*- 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
執行結果:
我的問題是:為什么如圖紅色標記的這一部分,也就是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
相關文章:
1. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處2. 視頻文件不能播放,怎么辦?3. node.js - nodejs開發中常用的連接mysql的庫4. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?5. mysql - 把一個表中的數據count更新到另一個表里?6. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?7. mysql 查詢身份證號字段值有效的數據8. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題9. visual-studio - Python OpenCV: 奇怪的自動補全問題10. Python爬蟲如何爬取span和span中間的內容并分別存入字典里?
