\$\begingroup\$
\$\endgroup\$
This is sort of a follow up to my post yesterday. I'm a relative newbie to Python and before I made a d20 dice roller for RPGs. Now I've made a dice roller for any type of dice, and I would love some feedback on this code.
from random import randint
def roll(sides, number_of_dice):
"""Rolls Dice."""
return [randint(1, sides) for i in range(num_of_dice)]
prompt = """
Would you like to roll the same combination of dice {}?
Please type 'yes', 'no', or 'quit'
"""
# Main Program
name = raw_input("\nPlease tell me your name > ")
print """
Hello {} and welcome to an RPG Dice Roller by Ray Weiss.
Please type quit when prompted to exit or use CNTRL-C.
Thanks to everyone at Stack Overflow etc. for the help.
""".format(name)
sides = input("\nHow many sides do you want on your dice? > ")
num_of_dice = input("\nHow many {} sided dice do you want to roll? >".format(sides))
results = roll(sides, num_of_dice)
print results
roll_again = raw_input(prompt.format(name))
while True:
if roll_again == "yes":
results = roll(sides, num_of_dice)
print results
roll_again = raw_input(prompt.format(name))
if roll_again == "no":
sides = input("How many sides do you want on your dice? > ")
num_of_dice = input("\nHow many {} sided dice do you want to roll? >".format(sides))
results = roll(sides, num_of_dice)
print results
roll_again = raw_input(prompt.format(name))
if roll_again == "quit":
print """
Thank you {} for using this RPG Dice Roller by Ray Weiss! Goodbye!
""".format(name)
break
asked Sep 21, 2012 at 19:11
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
I think the big thing here is to beware of external data. Assume that it could be garbage.
For instance:
- What happens if the user doesn't enter a name? -> Actually, not much apart from 2 spaces (rather than 1) in messages - relatively benign.
- What happens if the user enters "rabbit" sides? -> This value in any case needs to be transformed to an int for
roll
to work correctly otherwise a TypeError will be thrown.int("rabbit")
will throw a ValueError (see last item) - Similarly,
num_of_dice
also have to be validated as a positive integer (non-zero). - If the user enters something wrong for
roll_again
(say, "of course!"), you'll enter an infinite loop - The question probably needs to be brought inside the loop. - You'll want to use
raw_input
rather thaninput
in python2.Input
evaluates an expression, which does what you want here (enter a number, get an int back (unless of course it's a float!)), but should be regarded as avoid if at all possible.
answered Sep 21, 2012 at 21:50
-
\$\begingroup\$ Thanks! I'm not so sure how to do many of these things as a newbie but its more for me to learn! I appreciate it! \$\endgroup\$lerugray– lerugray2012年09月22日 12:47:32 +00:00Commented Sep 22, 2012 at 12:47
Explore related questions
See similar questions with these tags.
lang-py