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