python小白的基礎(chǔ)問題 關(guān)于while循環(huán)的嵌套
問題描述
源代碼如下:
# -*- coding:gb2312 -*-#站起來,坐下,站起來,轉(zhuǎn)5個(gè)圈,坐下。整個(gè)流程執(zhí)行10次Process1 = 1Process2 = 1while Process1 < 10: # 這個(gè)Process1 代表外面大的while循環(huán) print('='*5) print('第%d次執(zhí)行'%Process1) print('站起來') print('坐下') print('站起來') while Process2 <= 5: # 這個(gè)Process2 代表嵌套在里面的while小循環(huán)print('轉(zhuǎn)%d個(gè)圈'%Process2)Process2 = Process2 + 1 print('坐下') Process1 = Process1 + 1
執(zhí)行結(jié)果:
我的問題是:為什么如圖紅色標(biāo)記的這一部分,也就是Process2這一部分的內(nèi)循環(huán),在整個(gè)過程只執(zhí)行了一次,而不是隨著外面的整個(gè)大循環(huán)執(zhí)行10次? 我如何改進(jìn)才可以讓他隨著整個(gè)程序一直嵌套在里面循環(huán)下去?
問題解答
回答1:執(zhí)行第一次外循環(huán)之后, Process2 的值變成了 6, 在執(zhí)行第二次外循環(huán)及以后時(shí),它的值一直是 6, 所以內(nèi)循環(huán)不執(zhí)行. 如果你想讓它執(zhí)行, Process2的初始化應(yīng)該放到外循環(huán)里面.
Process1 = 1while Process1 < 10: # 這個(gè)Process1 代表外面大的while循環(huán) print('='*5) print('第%d次執(zhí)行'%Process1) print('站起來') print('坐下') print('站起來') Process2 = 1 while Process2 <= 5: # 這個(gè)Process2 代表嵌套在里面的while小循環(huán)print('轉(zhuǎn)%d個(gè)圈'%Process2)Process2 = Process2 + 1 print('坐下') Process1 = Process1 + 1回答2:
要把內(nèi)層循環(huán)的變量賦值放在外層循環(huán)里面才行。保證在每次外層循環(huán)時(shí),內(nèi)層循環(huán)變量都從1開始。不然,內(nèi)層循環(huán)變量第一次運(yùn)行后變成6,之后一直是6,導(dǎo)致后面不再執(zhí)行。
# -*- coding:gb2312 -*-#站起來,坐下,站起來,轉(zhuǎn)5個(gè)圈,坐下。整個(gè)流程執(zhí)行10次Process1 = 1while Process1 < 10: # 這個(gè)Process1 代表外面大的while循環(huán) print('='*5) print('第%d次執(zhí)行'%Process1) print('站起來') print('坐下') print('站起來') Process2 = 1 while Process2 <= 5: # 這個(gè)Process2 代表嵌套在里面的while小循環(huán)print('轉(zhuǎn)%d個(gè)圈'%Process2)Process2 = Process2 + 1 print('坐下') Process1 = Process1 + 1
相關(guān)文章:
1. Python處理Dict生成json2. (python)關(guān)于如何做到按win+R再輸入文件文件名就可以運(yùn)行?3. 想練支付寶對接和微信支付對接開發(fā)(Java),好像個(gè)人不可以,怎么弄個(gè)企業(yè)的4. mysql - Sql union 操作5. java - Mybatis 數(shù)據(jù)庫多表關(guān)聯(lián)分頁的問題6. 急急急!!!求大神解答網(wǎng)站評論問題,有大神幫幫小弟嗎7. javascript - 按鈕鏈接到另一個(gè)網(wǎng)址 怎么通過百度統(tǒng)計(jì)計(jì)算按鈕的點(diǎn)擊數(shù)量8. python - 如何使用websocket在網(wǎng)頁上動態(tài)示實(shí)時(shí)數(shù)據(jù)的折線圖?9. python - 請問這兩個(gè)地方是為什么呢?10. python2.7 - python 正則前瞻 后瞻 無法匹配到正確的內(nèi)容
