简体   繁体   English

Python为什么while循环控制有效

[英]Python Why Does This While Loop Control Work

So I was building a script and needed a conditional. 因此,我正在构建脚本,需要一个条件脚本。 I went with a variabled-while loop for control like so. 我使用了一个while变量循环进行控制。

while a == True

While coding it I forgot the variable and ended up with this: 在编码时,我忘记了变量,最​​终得到了这个:

while True: ## Num hands control loop
    try:
        v_NumHands = int(raw_input("Enter number of hands desired, 1 - 7:"))
        if (v_NumHands < 1) or (v_NumHands > 7): ## Checks num of hands is in range
            print("Not correct, try again.")
        else: break 
    except ValueError:
        print("Enter a number.")
print("Hands: %s") %(v_NumHands)

I figured that it would not work as the 'break' should break out of the 'if' conditional, but not the 'while loop.' 我认为它不起作用,因为“中断”应该脱离“ if”条件,而不是“ while循环”。 However it does work and I don't know why. 但是它确实有效,我不知道为什么。

So why does this work? 那为什么行得通呢?

I think you've discovered that break only breaks out of loops and not if conditionals :) 我认为您已经发现break只会中断循环,而不会if条件:)

Here are the docs 这是文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM