Roll the Dice Until You Get 6

I am supposed to write code that will roll dice and loop it automatically until it results 6 and then stop. My code only rolls once and repeats it endlessly.

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

while r < 6:
     print(r)
     continue
     if r == 6:
          print(r)
          break
1

2 Answers

You have to roll the dice again (aka inside the loop):

import random

mi, ma = 1, 6  # do not shadow built-ins `min` and `max`

while True:
    r = random.randint(mi, ma)
    print(r)
    if r == 6:
        break

Or with an assignment expression (using the walrus operator):

while (r := random.randint(mi, ma)) != 6:
    print(r)
# print(r)  # if you need to see the final 6

You need to generate the random number at each iteration as follows:

import random
min_=1
max_=6

while True:
     r = random.randint(min_, max_)
     print(r)
     if r == 6:
          print(r)
          break
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest