For Loop Not Breaking (Python)

后端 未结 8 662
春和景丽
春和景丽 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...")
    
    0 讨论(0)
  • 2021-01-22 12:10

    For loops in Python work like this.

    You have an iterable object (such as a list or a tuple) and then you look at each element in the iterable, storing the current value in a specified variable

    That is why

    for i in [0, 1, 2, 3]:
        print item
    

    and

    for j in range(4):
        print alist[j]
    

    work exactly the same. i and j are your storage variables while [0, 1, 2, 3] and range(4) are your respective iterables. range(4) returns the list [0, 1, 2, 3] making it identical to the first example.

    In your example you try to assign your storage variable count to some new number (which would work in some languages). In python however count would just be reassigned to the next variable in the range and continue on. If you want to break out of a loop

    1. Use break. This is the most pythonic way
    2. Make a function and return a value in the middle (I'm not sure if this is what you'd want to do with your specific program)
    3. Use a try/except block and raise an Exception although this would be inappropriate

    As a side note, you may want to consider using xrange() if you'll always/often be breaking out of your list early.

    The advantage of xrange() over range() is minimal ... except when ... all of the range’s elements are never used (such as when the loop is usually terminated with break)

    As pointed out in the comments below, xrange only applies in python 2.x. In python 3 all ranges function like xrange

    0 讨论(0)
  • 2021-01-22 12:11

    The for loop that you have here is not quite the same as what you see in other programming languages such as Java and C. range(0,5) generates a list, and the for loop iterates through it. There is no condition being checked at each iteration of the loop. Thus, you can reassign the loop variable to your heart's desire, but at the next iteration it will simply be set to whatever value comes next in the list.

    It really wouldn't make sense for this to work anyway, as you can iterate through an arbitrary list. What if your list was, instead of range(0,5), something like [1, 3, -77, 'Word', 12, 'Hello']? There would be no way to reassign the variable in a way that makes sense for breaking the loop.

    I can think of three reasonable ways to break from the loop:

    1. Use the break statement. This keeps your code clean and easy to understand
    2. Surround the loop in a try-except block and raise an exception. This would not be appropriate for the example you've shown here, but it is a way that you can break out of one (or more!) for loops.
    3. Put the code into a function and use a return statement to break out. This also allows you to break out of more than one for loop.

    One additional way (at least in Python 2.7) that you can break from the loop is to use an existing list and then modify it during iteration. Note that this is a very bad way to it, but it works. I'm not sure that this will this example will work in Python 3.x, but it works in Python 2.7:

    iterlist = [1,2,3,4]
    for i in iterlist:
        doSomething(i)
        if i == 2:
            iterlist[:] = []
    

    If you have doSomething print out i, it will only print out 1 and 2, then exits the loop with no error. Again, this is a bad way to do it.

    0 讨论(0)
  • 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."
    
    0 讨论(0)
  • 2021-01-22 12:24

    You can use while:

    times = 5
    guessed = False
    while times and not guessed:
        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...")
                times -= 1
    
    0 讨论(0)
  • 2021-01-22 12:28

    What @Rob Watts said: Python for loops don't work like Java or C for loops. To be a little more explicit...

    The C "equivalent" would be:

    for (count=0; count<5; count++) {
       /* do stuff */
       if (want_to_exit)
         count=10;
    }
    

    ... and this would work because the value of count gets checked (count<5) before the start of every iteration of the loop.

    In Python, range(5) creates a list [0, 1, 2, 3, 4] and then using for iterates over the elements of this list, copying them into the count variable one by one and handing them off to the loop body. The Python for loop doesn't "care" if you modify the loop variable in the body.

    Python's for loop is actually a lot more flexible than the C for loop because of this.

    0 讨论(0)
提交回复
热议问题