Let's walk through the process:
You already know what you need to generate random numbers.
import random
(or you could be more specific and say from random import randint
, because we only need randint
in this program)
- As you've already said it;
print("You rolled",random.randint(1,6))
"rolls the dice".
but it does it only once, so you need a loop to repeat it. A while loop is calling to us.
- You need to check if the user inputs
Y
. And you can simply do it with "Y" in input()
.
code version 1.
import random
repeat = True
while repeat:
print("You rolled",random.randint(1,6))
print("Do you want to roll again? Y/N")
repeat = "Y" in input()
code version 1.1 (A little better)
from random import randint
repeat = True
while repeat:
print("You rolled",randint(1,6))
print("Do you want to roll again?")
repeat = ("y" or "yes") in input().lower()
In this code, the user is free to use strings like yEs
, y
, yes
, YES
and ... to continue the loop.
Now remember, in version 1.1, since I used from random import randint
instead of import random
, I don't need to say random.randint(1, 6)
and simply radint(1,6)
will do the job.