python - Python - WHILE 循环嵌套在 FOR 循环中
问题描述
我试图实现这个输出:
0;12
1;24
2;36
3;48
4;60
...但我得到了这个:
0;12
1;12
2;12
3;12
4;12
这是代码:
iter = 0
count = 0
letter = 0
for iter in range(5):
while letter < len("hello, world"):
letter+=1
count+=1
print("Iteration " + str(iter) + "; count is: " + str(count))
我设法通过添加count*(iter+1)
而不是count
在打印语句中解决了这个问题,但我试图理解的是为什么每次新的迭代开始时计数变量都会重置。提前致谢。
解决方案
letter
始终为 13,因为它没有重新初始化。所以while循环只会执行一次。为了解决这个问题,
count = 0
for iter in range(5):
letter = 0
while letter < len("hello, world"):
letter+=1
count+=1
print("Iteration " + str(iter) + "; count is: " + str(count))
推荐阅读
- python - Pandas:使用Haversine公式进行插值
- reactjs - React Google Maps API 的问题 - 未捕获的 TypeError:无法读取 null 的属性“getCenter”
- php - 我想以分钟为单位获取当前时间和时间 h:i:s AM 之间的差异
- appium-android - Mobile Recorder 自动启动和关闭应用程序
- c++ - upper_bound 如何与自定义对象类型 val 一起工作?
- sass - 如何将 Sass 变量导出到 Javascript?
- vue.js - 添加 , 到数字输入框 vue
- xampp - XAMPP 无法打开 PHP 文件
- mysql - 如何在 MySQL 5.7 中使用变量实现按功能分区
- rust - 启用项目功能时启用 Rust nightly 功能