DEV Community


Posted on

How to fix an Endless Loop in Python?


This is my first time here on I need some help fixing a code.
See I'm learning Python from scratch and created this simple game program using Python that randomly rolls a dice in Visual Studio 2015.

But two problems have risen from my program. The first problem is that the dice doesn't exactly roll randomly. It will give me the random number but the numbers will not change until I close the program and only then do I close the program that it will give me another random set of numbers again.

The second problem I have found is when I run the code, it goes into an endless loop. I'm not sure how I am able to make this loop endless but I don't know how to stop it. If anyone can help me fix my mistakes, I'd really appreciate it.

Please find my code here.

import random
min = 1
max = 6
dice = random.randint(1, 6)
dice2 = random.randint(1, 6)

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":
    print "Rolling the dices..."
    print "The values are...."
    print dice
    print dice2

if(dice + dice2 == 6):
    print("You rolled a 6! You have been cursed!")
elif(dice + dice2 == 7):
    print("You rolled a 7! You have been blessed with money")
    print("You don't have any blessings")

roll_again = raw_input("Roll the dices again?")
Enter fullscreen mode Exit fullscreen mode

Thank you in advance.

Top comments (8)

mkartic profile image

You have assigned 'rolling_again' to 'yes' at the start of your program. Once you enter the 'while' loop, rolling_again's value is not changed in any way.

You have to put the entire block of code starting from the if condition to end of the program inside the while loop. That way, each iteration, you can get user input and proceed based on that.

Hope this helps.

crhodes2 profile image

Yes! It works! Thank you!

codemouse92 profile image
Jason C. McDonald

Regarding the random numbers, you need to seed random with a changing number. Not seeding, or always seeding with the same number, will result in the same random numbers being produced.

So, the most common way around this is to use the current time to seed random.

import random
from datetime import datetime

(Disclaimer: While this is what I've used for years in Python, I double-checked the exact syntax like I always do. This version comes from this StackOverflow answer)

crhodes2 profile image

It also worked out. Thank you!

tcratius profile image
Me, myself, and Irenne

My favourite is sticking this in the loop to stop it and ask for user input.

action = rawinput(" > ")

tcratius profile image
Me, myself, and Irenne

the other one I like using is, While not True, than in side your if statement make it True once you've done what you want.

kajigga profile image

On the topic of endless loops, try out Florian Rohrer's Endless Loop Challenge. It was a fun exercise.

crhodes2 profile image
crhodes • Edited

Just checked it out, and posted my own code there. It's fun! :D