Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 527
user3750528 Avatar asked Sep 16 '25 06:09

user3750528


2 Answers

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.

like image 176
Rob Watts Avatar answered Sep 17 '25 21:09

Rob Watts


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
like image 38
dt0xff Avatar answered Sep 17 '25 19:09

dt0xff