Python, refined rollDie()

Thanks to luthe over at the Arstehnica forums and Collin for their input.

I have fixed the following items:

  • rollDice has a body now! (I think)
  • Totally rewritten “retry” loop
  • Implemented formatting operator to simplify print statements (This is one powerful feature)
  • Added input validation for the variable sides

    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()
    
  • Python functions and modules (edit: now with more input checking and comments)

    I am progressing (albeit slowly) in python, but I seem to have a decent grasp on functions.

    In this sample rolldie function, I had an issue with random.randrange. If I specified a range of 6, it would roll 0-5 which is fine. Initially I mistakenly tried to correct for this by adjusting the input provided to random.randrange. A much better solution was to adjust the output of the random.randrange function by doing random.randrange +1.

    It was a simple problem with a very simple solution, but it is an important lesson:

    If a function is not giving you the output you desire; adjust the function, not the input.

    (cue “The More You know” music)

    #!C:/python25/
    #filename:rollDie.py
    #Version 0.5 - Improved error checking of luckyNumber and added comments
    
    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 user input and setup variables
        sides = int(raw_input('Enter the number of sides for the dice:'))
        luckyNumber = int(raw_input('Enter your Lucky number:'))
        count = 1
        value = random.randrange(sides) +1
    
        #Error checking the luckyNumber variable
        while luckyNumber <= 0:
            print 'Impossible to roll', luckyNumber,'!'
            luckyNumber = int(raw_input('Enter your Lucky number:'))
        while luckyNumber > sides:
            print 'You will never roll', luckyNumber, 'with only', sides, 'sides!\n'
            luckyNumber = int(raw_input('Enter your Lucky number:'))
    
        #OK luckyNumber is good, now to guess it at random
        while value != luckyNumber:
            print value
            value = random.randrange(sides) +1
            count += 1
        print 'Finally got the number ', luckyNumber, '! It only took', count, 'Guesses!'
    
        #We guessed the lucky number, query for retry
        tryAgain = str (raw_input('Want to try again? Type yes,no or explain\n'))
        while tryAgain == 'explain':
            print rollDie.__doc__
            tryAgain = str (raw_input('Want to try again? Type yes,no or explain\n'))
        if tryAgain == 'no':
            print 'Ok we are done!'
            run = False
        elif tryAgain == 'yes':
            pass
    ###########################################################################
    
    rollDie()
    

    Python

    Well instead of playing with LFS, I have started toying around with Python, and so far I am loving the readability and ease of use. Here is the very basic program I wrote that calculates the perimeter and area of a user defined square. This is only after about 6 hours of reading and playing around so I think I am doing pretty good:

    
    #!/usr/var/python
    #filename: flow_control
    
    debug = 0
    repeat = 'yes'
    
    print 'This application calculates the perimeter and area of a user defined square.'
    
    if debug == 1:
        print '**begin user data collection function** \n'
    
    while repeat == 'yes':
        width = float (raw_input('\nEnter the measured width: '))
        length = float (raw_input('Enter the measured length: '))
    
        if debug == 1:
            print '**Begin caculation function** \n'
    
        perimeter = 2 * (width + length)
        area = (length * width)
    
        if debug == 1:
            print '**Begin display of calculated measurements** \n'
    
        print '\nI have calculated the perimeter as:', perimeter
        print 'I have calculated the area as:', area
    
        repeat = str (raw_input('\nDo you want to try again? Type yes or no. \n'))
    
    else:
            print 'Ok, we are done here. Thanks!'