while loop wont stop running in python

Question:

I am working on a crash game in python and im trying to make it crash when a value hits 1,50, or 100 but it keeps going. Does anyone know why?

import random
import time

game = 1
num = 1.00

while game == 1:
    num += .01
    print(round(num, 2))
    time.sleep(.1)
    if game != 1:
        print("Crash!")
        break

while game == 1:
    crash = random.randint(1, 100)
    time.sleep(.1)
    if crash == 1 or crash == 50 or crash == 100:
        game -= 1
    else:
        break
Asked By: Omegadude52

||

Answers:

In first while loop game’s value never changes from 1 therefore never exits the first while loop

BTW you do not have to break the loop because once game != 1 it will won’t enter the loop again.

I think you mean to use only the second while loop you have written – so you can delete the first one and remove the else from the second – no need for it for the same reason you do not need the break in the first loop.

so if I understand your intention correctly than the code should be:

import time

game = 1

while game == 1:
    crash = random.randint(1, 100)
    time.sleep(.1)
    if crash == 1 or crash == 50 or crash == 100:
        game -= 1
Answered By: Ben Hazout

If you’re new to computer science, it can sometimes be useful to "play computer" when looking at code. Look at each step of the code and try to imagine what would happen. In a language like python, you can even test these statements one at a time to make sure they do what you think they do.

Let’s skip to the important part.

The state of the memory is game and num both equal 1.

while game == 1: # loop until game is not 1
    num += .01 # add 0.01 to num
    print(round(num, 2)) #print round(num, 2); 1.01 the first time
    time.sleep(.1) # sleep for 1 10th of a second
    if game != 1: #game was not changed before this point, so game=1
        print("Crash!") # this will never execute, ignore it.
        break
# End of the loop: execution flow return to the start again, with num=1.01

You see the problem? This will never exit because game is never altered in the loop, this will continue to loop forever. The second loop won’t ever even be reached because it’s going to be stuck in the first one.

Answered By: pizzamonkey
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.