Tuomas Harju
Tuomas Harju

Reputation: 3

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```

Upvotes: 0

Views: 1605

Answers (2)

user2390182
user2390182

Reputation: 73470

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

Upvotes: 4

Oguzhan Karaahmetoglu
Oguzhan Karaahmetoglu

Reputation: 34

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

Upvotes: 1

Related Questions