4

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.

2
  • It's not ending because you don't use break ;-) Commented Jun 18, 2014 at 0:32
  • The right way to break out of a loop in Python is to use break. Pythonic style typically discourages rather than celebrates obfuscatory workarounds. Commented Jun 18, 2014 at 0:36

8 Answers 8

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

(Implication: Assignment to the count variable inside the loop is pointless.)
So could I change around a few thing likes this and get it to break early: for count in range(0, 5, count2) then assign count2 = 10 if the number matches?
No. Assigning a new value to count2 would not change the any values held by the generator that range(0,5,count2) creates.
4

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

2 Comments

Sorry, I should have mentioned that part of the challenge is to continue using the for loop. The while loop does work though. I did test that.
The right way to break out of a loop in Python is to use break. Pythonic style typically discourages rather than celebrates obfuscatory workarounds. This ain't Perl :-P.
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 ranges function like xrange

1 Comment

Note that xrange is only applicable to Python 2. In Python 3, there is no xrange.
0

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

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.