简体   繁体   中英

How do I fix my (supposedly while-loop or if-statement) dice-simulator in Python so it prints the amount of tries its taken before landing on a 6?

So, I'm a little stuck on a coding assignment of mine – I'm supposed to write a code in Python simulating the throw of a dice, in which the program randomizes numbers between 1-6 until it "lands" on the number 6; the program is furthermore supposed to count the number of tries it has "thrown the dice" before "landing" on a 6, and print out print("It took", n, "tries to get a six.") in which n = the number of tries it has thrown the dice before landing on a 6.

This is what I've come up with thus 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

But, alas, it only prints out "It took 1 try to get a 6." in the result window and shows blank in the result window whenever the "dice" doesn't land on a 6. I guess what my question is, is: how do I get it to count all the tries before landing on a 6, and subsequently print the said amount of tries in combination with the statement print("It took", n, "amount of tries to get a 6.")?

You need to write your break command into an if-statement. In your current code it breaks within the first iteration.

As this is an assigment i dont want to tell you everything. But that while loop condition won't get you there. Try writing a blank while loop with a break-condition, think about it.

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM