Search code examples
pythonrandomwhile-loopdice

Need help fixing random number


I'm learning Python and was working on the random dice throw. When I run it, it repeats the same number that is first shown after asked if you want to play again. I need help finding where I'm going wrong here.

I've tried moving code around and also putting different varieties of the code. I'm just stumped.

import sys
import random
import time


greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
die = random.randint(0, 6)

print(greeting)
time.sleep(2)

answer = input("Want to play?")

while answer == "yes" or answer == "y":
    print(roll)
    time.sleep(2)
    print(die)
    answer = input("Want to play again?")
print("Thanks for playing!")

This is what I get:

Welcome to my Dice Game!
Want to play?yes
Lets roll this die!
5
Want to play again?yes
Lets roll this die!
5
Want to play again?y
Lets roll this die!
5

Solution

  • You need to recompute the value of the dice each time in your loop like:

    import sys
    import random
    import time
    
    
    greeting = "Welcome to my Dice Game!"
    roll = "Lets roll this die!"
    
    
    print(greeting)
    time.sleep(2)
    
    answer = input("Want to play?")
    
    while answer == "yes" or answer == "y":
        print(roll)
        time.sleep(2)
        die = random.randint(0, 6) # recompute it here instead
        print(die)
        answer = input("Want to play again?")
    print("Thanks for playing!")