For Loop Not Breaking (Python)

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

    In Python the for loop means "for each item do this". To end this loop early you need to use break. while loops work against a predicate value. Use them when you want to do something until your test is false. For instance:

    tries = 0
    max_count = 5
    guessed = False
    
    while not guessed and tries < max_count:
        guess_number = int(input("Enter any number between 0 - 10: "))
        if guess_number == rand_number:
            print("You guessed it!")
            guessed = True
        else:
            print("Try again...")
        tries += 1
    
    0 讨论(0)
  • 2021-01-22 12:32

    What you probably want is to use break and to avoid assigning to the count variable.

    See the following, I've edited it with some comments:

    import random
    
    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): instead of count, use a throwaway name
    for _ in range(0, 5): # in Python 2, xrange is the range style iterator
        guess_number = int(input("Enter any number between 0 - 10: "))
        if guess_number == rand_number:
            print("You guessed it!")
            # count = 10 # instead of this, you want to break
            break
        else:
            print("Try again...")
            # count += 1 also not needed
    
    0 讨论(0)
提交回复
热议问题