【问题标题】:Why does this code going through infinite? [closed]为什么这段代码会无限循环? [关闭]
【发布时间】:2021-01-04 03:39:02
【问题描述】:

为什么下面的代码会产生无限循环? 第一个回报是 9 它不再等于 10。 我无法得到它。 谁能简单解释一下?

n = 10
while True:
    print(n, end=' ')
    n = n - 1
print('Done!')

【问题讨论】:

  • 你在哪里检查n是否等于10?还要修正你的缩进。
  • 我编辑了你的代码并猜测了一个适当的缩进。 while True: 永远不会跳出循环。你的意思是像while n > 0: 这样的东西吗?

标签: python loops


【解决方案1】:

while True 永远存在,因为True 永远是True

如果你想在n变成0时结束循环,试试:

n = 10
while n > 0:
    print(n, end=' ')
    n = n - 1
    print('Done!')

输出:

10 Done!
9 Done!
8 Done!
7 Done!
6 Done!
5 Done!
4 Done!
3 Done!
2 Done!
1 Done!

【讨论】:

    【解决方案2】:
    n = 10                  # Here you are initializing the variable n as 10
    while True:             # Now you are saying, while True (this means forever because you are saying, as long True is true, do this)
        print(n, end=' ') 
        n = n - 1
    print('Done!')
    

    我相信你想验证 n 等于 10,所以,条件必须改变:

    n = 10                  # Here you are initializing the variable n as 10
    while n = 10:           # Now you are saying, while n = 10 (this means only once because the loop changes the value of n)
        print(n, end=' ') 
        n = n - 1
    print('Done!')
    

    【讨论】:

      【解决方案3】:

      您正在使用没有 break 语句的 while True 使用这个

      n = 10
      while n>0:
          print(n, end=' ')
          n = n - 1
          print('Done!')
      

      或者

      n = 10
      while True:
          print(n, end=' ')
          n = n - 1
          print('Done!')
          if(n==0):
              break;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 2014-02-13
        相关资源
        最近更新 更多