简体   繁体   中英

how to roll a die until 20 rolls 3 or lower are rolled Python

I've been trying to write it so it pulls from

roll_dice = random.randint(1,6)

but its only been set to one number so it's always equal to the same number. here's the full code:

import random

roll_dice = random.randint(1,6)

rolls = 0
check = 0
while check <= 20:
    roll_dice
    if roll_dice < 4:
        check = check +  1
        rolls =  rolls + 1
    elif roll_dice > 0:
        rolls += rolls + 1
    elif check == 20:
        print("it took", rolls, "to reach 20 rolls under 3")   

Put the roll_dice = random.randint(1, 6) inside the while loop so that each iteration the value of roll_dice changes, and is a random number from 1 to 6.

Ie, without changing the structure of your code too much,

import random
rolls = 0
check = 0
while check <= 20:
    rolls =  rolls + 1 #add 1 to rolls counter
    roll_dice = random.randint(1,6) #Set roll_dice to random int from 1-6
    if roll_dice < 4: #if it is 3 or lower, add 1 to check
        check = check +  1
    if check == 20: #if 20 rolls of 3 or less, then print and stop loop
        print("it took", rolls, "rolls to reach 20 rolls under 3")
        break

Sample Output:

it took 32 rolls to reach 20 rolls under 3

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