For Loop Not Breaking (Python)

后端 未结 8 666
春和景丽
春和景丽 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:07

    As your question states NOTE: Part of the challenge is to use the FOR loop, not the WHILE loop and you don't want to use break, you can put it in a function and return when the correct number is guessed to break the loop.

    import random
    
    
    def main():
        guess_number = 0
        count = 0
        rand_number = 0
    
        rand_number = random.randint(0, 10)
    
        print("The guessed number is", rand_number)
    
        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!")
                return
            else:
                print("Try again...")
    

提交回复
热议问题