patternpythonMinor
Random D20 number generator
Viewed 0 times
randomd20numbergenerator
Problem
I'm teaching myself code using Zed Shaw's Learn Python The Hard Way, and I got bored during one of the memorization lessons so I thought I would make a random D20 number generator for when I play RPGS.
How can I make this code better? Is there anything stupid I'm doing?
Eventually I would love to add functionality to have it ask you what kind and how many dice you want to role, but for now a review of what I've done so far would really help.
How can I make this code better? Is there anything stupid I'm doing?
import random
name = raw_input('Please Type in your name > ')
print "\nHello %s & welcome to the Random D20 Number Generator by Ray Weiss.\n" % (name)
first_number = random.randint(1, 20)
print first_number
prompt = ("""
Do you need another number? Please type yes or no.
""")
answer = raw_input(prompt)
while answer == "yes":
print random.randint(1, 20)
answer = raw_input(prompt)
if answer == "no":
print "\nThank you %s for using the D20 RNG by Ray Weiss! Goodbye!\n" % (name)Eventually I would love to add functionality to have it ask you what kind and how many dice you want to role, but for now a review of what I've done so far would really help.
Solution
Here's my take:
Changes as compared to your version:
from random import randint
name = raw_input('Please Type in your name > ')
print """
Hello {} & welcome to the Random Number Generator by Ray Weiss.
""".format(name)
upper = int(raw_input('Enter the upper limit > '))
n = int(raw_input("How many D{} you'd like to roll? ".format(upper)))
for _ in xrange(n):
print randint(1, upper)
print """
Thank you {} for using the D{} RNG by Ray Weiss! Goodbye!
""".format(name, upper)Changes as compared to your version:
- directly import
randintbecause it's the only function you use inrandom;
- use the new string formatting method (
str.format);
- take the upper bound from user instead of hard-coding 20;
- take the number of rolls from user instead of repeatedly asking if that's enough;
- use a loop to make the repetition actually work. The self-repeating code asking the user if we should continue is now gone.
Code Snippets
from random import randint
name = raw_input('Please Type in your name > ')
print """
Hello {} & welcome to the Random Number Generator by Ray Weiss.
""".format(name)
upper = int(raw_input('Enter the upper limit > '))
n = int(raw_input("How many D{} you'd like to roll? ".format(upper)))
for _ in xrange(n):
print randint(1, upper)
print """
Thank you {} for using the D{} RNG by Ray Weiss! Goodbye!
""".format(name, upper)Context
StackExchange Code Review Q#15778, answer score: 8
Revisions (0)
No revisions yet.