简体   繁体   中英

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 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.' 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 :)

Here are the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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