For Loop Not Breaking (Python)

后端 未结 8 755
春和景丽
春和景丽 2021-01-22 11:35

I\'m writing a simple For loop in Python. Is there a way to break the loop without using the \'break\' command. I would think that by setting count = 10 that the exit condition

8条回答
  •  甜味超标
    2021-01-22 12:14

    As others have stated the Python for loop is more like a a traditional foreach loop in the sense that it iterates over a collection of items, without checking a condition. As long as there is something in the collection Python will take them, and if you reassign the loop variable the loop won't know or care.

    For what you are doing, consider using the for ... break ... else syntax as it is more "Pythonic":

    for count in range(0, 5):
        guess_number = int(input("Enter any number between 0 - 10: "))
        if guess_number == rand_number:
            print("You guessed it!")
            break
        else:
            print("Try again...")
    else:
        print "You didn't get it."
    

提交回复
热议问题