January 16, 2008
Python, refined rollDie()
Thanks to luthe over at the Arstehnica forums and Collin for their input.
I have fixed the following items:
I really, really like the formatting operator. It just makes for much cleaner and readable, reliable code; versus inserting variables into print statments.
#!C:/python25/
#filename:rollDie.py
#Version 0.6 - Improved error checking of sides, a improved retry loop and formatting operators!
import random
def rollDie():
#DocString
'''\nUses a random number generator to guess a user specified number.
Uses two user defined integers (one to define the set, and one as a target number) and then tries to guess at random using random.randrange.\n'''
#rollDie intro
print 'Welcome to the Lucky Number Program!\n'
run = True
while run == True:
#query for sides and error check
sidesCheck = False
while sidesCheck == False:
sides = int(raw_input('Enter the number of sides for the dice:'))
if sides >= 2:
sidesCheck = True
else:
print 'Impossible to roll a die with %s sides!' % (sides, )
#query for luckyNumber and error check
luckyNumberCheck = False
while luckyNumberCheck == False:
luckyNumber = int(raw_input('Enter your Lucky number:'))
if (0 < luckyNumber <= sides):
luckyNumberCheck = True
else:
print 'You will never roll %s with a %s sided die!\n' % (luckyNumber, sides, )
#Input is valid, now to guess it at random
value = random.randrange(sides) +1
count = 1
while value != luckyNumber:
print value
value = random.randrange(sides) +1
count += 1
print 'Finally got the number %s! It only took %s guesses!' % (luckyNumber, count, )
#We guessed the lucky number, query for retry
retryLoop = True
while retryLoop == True:
tryAgain = str (raw_input('Want to try again? Type yes,no or explain\n'))
if tryAgain == 'yes':
retryLoop = False
elif tryAgain == 'no':
print 'Ok we are done!'
retryLoop = False
run = False
elif tryAgain == 'explain':
print rollDie.__doc__
###########################################################################
rollDie()
Filed by RawCode at 6:15 am under Python
Comments Off
2 Comments