Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python While循环分配_Python_Loops_While Loop_Variable Assignment_Break - Fatal编程技术网

Python While循环分配

Python While循环分配,python,loops,while-loop,variable-assignment,break,Python,Loops,While Loop,Variable Assignment,Break,在这种情况下,为什么while-True循环应用于count?我不明白为什么布尔值在计算计数的结果。正确的语法不是: # Finicky Counter # Demonstrates the break and continue statements count = 0 while True: count += 1 # end loop if count greater than 10 if count > 10: break # skip 5 if count

在这种情况下,为什么while-True循环应用于count?我不明白为什么布尔值在计算计数的结果。正确的语法不是:

# Finicky Counter
# Demonstrates the break and continue statements

count = 0
while True:
  count += 1
  # end loop if count greater than 10
  if count > 10:
   break
  # skip 5
  if count == 5:
    continue
  print(count)

input("\n\nPress the enter key to exit.")

任何澄清这一点的帮助都将不胜感激。

count
为0,因此
while count
甚至不会进入循环,因为在布尔上下文中0为False

Python没有类似于
repeat。。。直到(条件)
在某些其他语言中找到。因此,如果您希望循环总是开始,但只有在条件变为真时才结束,通常的方法是将条件设置为刚好
true
——显然,这总是真的——然后在循环内显式测试条件,并使用
break
进行中断


为了回答您的评论,这里正确的只是值
true
,正如我所说的,这种情况永远都会发生。

如果您在调试器中一步一步地遵循代码(一个简单的ide,它允许使用PyScripter)

我只想说几句话:

  • 而True
    是一个无止境的循环。它只能由
    break
    return
    语句留下
  • 因此,循环将一直运行,直到满足条件
    count>10
    。中断将终止循环,并执行下一个命令(
    input…
  • 如果
    count==5
    continue
    告诉python立即跳转到循环的开头,而不执行以下语句(因此不打印“5”)

但是:在调试器中遵循代码

while循环的语法是“while condition”。while循环下的块将一直执行,直到任一条件的计算结果为False或执行中断命令为止。“while True”表示条件始终为True,循环不会停止,除非执行中断。这是一个经常使用的python习惯用法,因为python没有一个

简单地说:它没有<代码>为True时:将永远循环。
中断
是唯一可以停止循环的东西。如果while循环没有测量计数,为什么它会永远循环?那么什么是真的呢?
true
是Python中内置的布尔值
而x:
在每次迭代中查看
x
,如果
bool(x)
True
,则继续循环,否则停止。由于
x
在这里是
True
bool(True)
始终是
True
,因此循环永远不会停止(好吧,除了其他停止它的东西-异常或
中断
语句)。
while count: