简体   繁体   中英

For Loop Not Breaking (Python)

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 would be met and the loop would stop. But that doesn't seem to be the case.

NOTE: Part of the challenge is to use the FOR loop, not the WHILE loop.

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):
    guess_number = int(input("Enter any number between 0 - 10: "))
    if guess_number == rand_number:
        print("You guessed it!")
        count = 10
    else:
        print("Try again...")
        count += 1

I'm new to programming, so I'm just getting my feet wet. I could use a 'break' but I'm trying figure out why the loop isn't ending when you enter the guessed number correctly.

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 .

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

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 range s function like xrange

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

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.

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

As others have stated the Python for loop is more like aa 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."

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...")

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