【问题标题】:Coverting for loop to a while loop Python将 for 循环转换为 while 循环 Python
【发布时间】:2021-04-02 15:31:07
【问题描述】:

我正在尝试将此 for 循环转换为 while 循环,但我正在苦苦挣扎。它应该具有相同的输出

low = 3
hi = 50
total = 0
for m in range (hi, low-1,-2):
      total = total + m
print("Total is", total)

【问题讨论】:

标签: python


【解决方案1】:
low = 3
hi = 50
total = 0
m = hi
while m>low-1
   total = total + m
   m = m-2
print("Total is", total)

【讨论】:

  • 欢迎堆栈溢出。为您的代码提供评论总是有帮助的,请考虑编辑您的答案以解释发生了什么
【解决方案2】:

这样的事情会起作用:

low = 3
hi = 50
total = 0

# summing every 2nd number from 50 down to 4, inclusive 
# (including hi=50, excluding low-1=2)
for m in range(hi, low-1,-2):
    print(m)
    total = total + m
print("Total is", total)

print("---")
total = 0
i = hi # set index to hi
while i >= low: # as long as index is greater than or equal to low,
    print(i)
    total += i
    i -= 2 # decrease index by 2
print("Total is", total)

如果你比较这两个代码,你会发现它们确实是相等的。

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 2017-04-26
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2013-09-24
    相关资源
    最近更新 更多