久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:153日期: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 編程
相關文章:
主站蜘蛛池模板: 连江县| 郓城县| 宾阳县| 双鸭山市| 明星| 大城县| 霍州市| 双柏县| 贵阳市| 徐州市| 汶川县| 颍上县| 富顺县| 和林格尔县| 岳阳市| 张家川| 屏南县| 怀集县| 额尔古纳市| 隆尧县| 来安县| 资兴市| 荥经县| 达孜县| 肥乡县| 宾川县| 罗甸县| 新龙县| 台山市| 遂川县| 和龙市| 诏安县| 呼和浩特市| 徐州市| 和政县| 独山县| 孝义市| 马尔康县| 江西省| 新津县| 黄大仙区|