Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dice Roller
#1
import random


def dice():
    sides = [1, 2, 3, 4, 5, 6]
    rollDice = input('roll? ')
	
    if rollDice == 'y':
        i = random.choice(sides)
        print(i)
        dice()

    elif rollDice == 'n':
        quit()
    
    else:
        print('invalid entry')
        dice()

dice()
Reply
#2
dice roller ?
import random

def dice():
    sides = 6
    count = 1
    while True:
        roll_dice = input('roll ? >> ')
        if roll_dice in ['y', '']:
            line = ''
            for i in range(count):
                line += str(random.choice(range(1, sides + 1))) + "  "
            print(line)
        elif roll_dice.startswith('sides'):
            sides = int(roll_dice[6:])
            print('using a {0} sided dice'.format(sides))
        elif roll_dice.startswith('count'):
            count = int(roll_dice[6:])
            print('using {0} dice'.format(count))
        elif roll_dice == 'n':
            break
        else:
            print('invalid entry')

dice()
99 percent of computer problems exists between chair and keyboard.
Reply
#3
@Windspar, I like to keep it simple.
Reply
#4
Only problem I see with your code. Is those nasty recursive calls.
Using loops is a better solution.
import random

def dice():
    while True:
        roll_dice = input('roll ? >> ')
        if roll_dice in ['y', '']:
            print(random.choice(range(1, 7)))
        elif roll_dice == 'n':
            break
        else:
            print('invalid entry')

dice()
99 percent of computer problems exists between chair and keyboard.
Reply
#5
instead of
print(random.choice(range(1, 7)))
keep it simple and better use
print(random.randint(1, 6))
https://docs.python.org/3/library/random...r-integers
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  A CLI based Dice Roller. Ablazesphere 10 6,563 Oct-26-2018, 11:41 AM
Last Post: snippsat
  Dice roller with Tkinter GUI Yojul 1 6,241 Oct-24-2018, 01:40 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020