繁体   English   中英

while 循环:数字小于 Python 中的数字

[英]while loop: number less than number in Python

这是我第一次在这里发帖。 抱歉,如果这不是正确的方法。 在下面的代码中,有三个循环迭代。 我能理解为什么。 但我需要它只有 2。有没有办法做到这一点?

weeks_x = 0
weeks_year = 52

count = 0

while weeks_x < weeks_year:
   weeks_x = weeks_x + 25
   count = count + 1

尝试使用简单的print语句调试您的代码

weeks_x = 0
weeks_year = 52

count = 0

while weeks_x < weeks_year:
   weeks_x = weeks_x + 25
   count = count + 1
   print(f'Iteration Number {count} and weeks_x is {weeks_x}')

output 使循环运行 3 次的原因变得清晰

Iteration Number 1 and weeks_x is 25
Iteration Number 2 and weeks_x is 50
Iteration Number 3 and weeks_x is 75

因为只有在第 3 次迭代之后, weeks_x的值才足以打破这个条件weeks_x < 52它持续 3 圈

您可以限制循环运行的次数

weeks_x = 0
weeks_year = 52

count = 0

# while weeks_x < weeks_year: # REMOVE THIS
while count < 2: # ADD THIS
   weeks_x = weeks_x + 25
   count = count + 1
   print(f'Iteration Number {count} and weeks_x is {weeks_x}')

添加print()语句对调试很有用:

weeks_x = 0
weeks_year = 52
count = 0
while weeks_x < weeks_year:
    print('weeks_x:', weeks_x, '- weeks_year', weeks_year)
    weeks_x = weeks_x + 25
    count =+ 1

output:

weeks_x: 0 - weeks_year 52
weeks_x: 25 - weeks_year 52
weeks_x: 50 - weeks_year 52

如果您特别需要两次循环迭代:

weeks_x = 0
weeks_year = 52
count = 0
while count < 2:
    print('weeks_x:', weeks_x, '- weeks_year', weeks_year)
    weeks_x = weeks_x + 25
    count =+ 1

count变量正在计算循环次数。

或者, weeks_x * 2将给出与循环相同的结果 - 否则,如果有需要这样做的功能,我建议使用range()查看for loops

在while之前初始化

weeks_x = 0
weeks_year = 52

count = 0

weeks_x += 25
while weeks_x < weeks_year:
  count += 1
  print('Count {}'.format(count), 'Week Value {}'.format(weeks_x), sep='-->', end='\n')
  weeks_x += 25

Output:-

Count 1-->Week Value 25
Count 2-->Week Value 50

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM