Dice rolling simulator in Python
Dice rolling simulator in Python
Lets walk through the process:
You already know what you need to generate random numbers.
import random
(or you could be more specific and sayfrom random import randint
, because we only needrandint
in this program)- As youve 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 withY 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 dont need to say random.randint(1, 6)
and simply radint(1,6)
will do the job.
This is for python 3
import random
repeat=Y
while repeat == Y:
print(Rolling the dice)
print(random.randint(1,6))
repeat =input(Do you wanna roll again Y/N?)
if repeat==Y:
continue
Dice rolling simulator in Python
I just started learning Python three days ago, but this is what I came up with for Python 3, and it works:
import random
question = input(Would you like to roll the dice [y/n]?n)
while question != n:
if question == y:
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
print(die1, die2)
question = input(Would you like to roll the dice [y/n]?n)
else:
print(Invalid response. Please type y or n.)
question = input(Would you like to roll the dice [y/n]?n)
print(Good-bye!)