Search code examples
pythonloopsfor-looprandomwhile-loop

How do I fix my dice-simulator in Python so it prints the amount of tries its taken before landing on a 6?


I'm using Python to simulate the throw of a dice, in which the program randomises numbers between 1-6 until it lands on the number 6. Furthermore, the program is supposed to count the number of tries it has thrown the dice before landing on a 6, and print out "It took x amount of tries to get a six." in which x is the number of tries it has thrown the dice before landing on a 6.

My code so far:

import random

dice = random.randint(1,6)
n = 0

while dice == 6:
    n = n + 1
    print("It took", n, "tries to get a 6.")
    break

For some reason, the program only prints "It took 1 try to get a 6." in the terminal and shows completely blank whenever the dice doesn't land on a 6. How do I get it to count the amount of attempts before landing on a 6, as well as print the amount of tries in combination with the statement print("It took", n, "amount of tries to get a 6.")?


Solution

  • The usual pattern for repeating an action an unknown number of times is to use a while True loop, and then break out of the loop when the exit condition is satisfied.

    rolls = 0
    
    while True:
        die = random.randint(1, 6)
        rolls += 1
    
        if die == 6:
            break
    
    print("It took", rolls, "tries to get a 6.")