【问题标题】:Transform For loop into while loop将 For 循环转换为 while 循环
【发布时间】:2022-12-04 10:03:46
【问题描述】:
s=0

for i in range(3,20,2):
    if i>10:
        break
    else:
        s=s+i
    
print(s)

如何将此代码转换为 while 循环?

我不知道如何包括该步骤。

【问题讨论】:

    标签: python for-loop while-loop


    【解决方案1】:
    s = 0
    i = 3
    while i<10:
        s+=i
        i+=2
    print(s)
    

    【讨论】:

      【解决方案2】:

      如果您想在 i>10 时中断循环,那么为什么要运行循环直到 20?任何方式你都可以试试这个

      s,i=0,3
      while i<=20:
          if i>10:
              break
          else:
              s=s+i
          i+=2
      print(s)
      

      【讨论】:

        猜你喜欢
        • 2018-02-22
        • 2017-04-26
        • 2018-08-19
        • 1970-01-01
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        相关资源
        最近更新 更多