【问题标题】:I got different results for a while loop and for loop in python (check the codes)我在 python 中的 while 循环和 for 循环得到了不同的结果(检查代码)
【发布时间】:2020-02-07 17:46:54
【问题描述】:

对于第一个代码:

num = 1

while num<=100:
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")
    num+=1

输出:1 2

对于第二个代码:

for num in range(1, 101):
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")

输出:

1 2 4 7 8 11 13 14 16 17 19 22 23 26 28 29 31 32 34 37 38 41 43 44 46 47 49 52 53 
56 58 59 61 62 64 67 68 71 73 74 76 77 79 82 83 86 88 89 91 92 94 97 98

【问题讨论】:

  • 您的第一个代码是无限的。我不确定你是如何得到1 2 作为输出的。
  • 在while循环中反转条件并将结果打印放在里面。你跳过num增量
  • @Austin 说了什么。在您的第一条语句的 if 条件中,您不会在继续之前增加计数器,因此 num%3 始终为真,之后可能会冻结您的程序。
  • @Austin 它只有continues 是 3 或 5 的倍数,而 1 和 2 不是。

标签: python python-3.x loops for-loop while-loop


【解决方案1】:

您需要在继续之前添加增量

num = 1
while num<=100:
    if num%3==0 or num%5==0:
        num += 1
        continue
    print (num)
    num+=1

【讨论】:

    【解决方案2】:

    您需要编辑您的while 代码才能获得相同的结果。在你的while循环中如果num%3 == 0 or num%==5,那么程序没有执行num += 1,所以你的程序不会递增1。你需要这样改变:

    num=0
    while num <= 100:
        num+=1
        if num%3==0 or num%5==0:
            continue
    
        print (num, end=" ")
    

    【讨论】:

      【解决方案3】:

      您的代码不会在 if 语句内的 while 循环中调用增量 1,它永远不会超过 3。

      【讨论】:

        【解决方案4】:

        这是一个无限循环。您的程序在达到 num == 3 后永远不会终止。它转到 if 语句,然后 continue 将其带回 while 检查。

        【讨论】:

          【解决方案5】:

          使用下面的逻辑

                  num = 1
          
                  while num <= 100:
                      if num % 3 == 0 or num % 5 == 0:
                          num += 1
                          continue
                      print(num, end=" ")
                      num += 1
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-04-26
            • 1970-01-01
            • 2012-09-19
            • 1970-01-01
            • 2021-10-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多