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!'
    

    I choose you… LFS!

    The urge to play around with linux is rising. Every time this occurs I always get pretty wrapped up in the project since I generally have a specific goal I am trying to attain. This time I want to build Linux; starting from bootstrapping to my end goal of network connectivity with SSH. So I have decided to go with LFS. ] It tries to teach you the role of all the packages you need to get a very basic system up and running.

    I want to purchase a separate computer to install this on so I don’t hose my current slackware box which I have servicing my network acceptably.

    TSA: Quit shuffling and looking at everyone else

    From Stonetable:

    The Washington Post is running an article about how the TSA is training agents on how to detect “stress, fear and deception” among travelers waiting in line.

    If you are traveling I really hope you are not having a bad day, feeling sick, worried about something, or have a medical condition that affects motor functions as you might be detained and searched.

    From the article:

    The teams have referred more than 40,000 people for extra screening since January 2006. Of those passengers, nearly 300 were arrested on charges including carrying concealed weapons and drug trafficking. TSA officials will not say whether the screeners have helped nab potential terrorists, but they say terrorists and other lawbreakers exhibit the same behavioral clues.

    This new training doesn’t make me feel any safer when it has a success rate of only 0.0075%.

    Another day, another WoD

    I have been busy running in some Solo II action (autocrossing) for the past two days so my time with crossfit has been low. However I can say with full authority that two days of spirited driving are enough to really work your shoulders and hands.

    Today’s WoD is:
    “Diane”

    21-15-9 reps of:
    225 pound Deadlift
    Handstand push-ups

    I LOL’d when I saw what it was. There is *NO WAY* I can do handstand pushups or 225 lbs of deadlift. So I did the following:

    21-15-9 reps of:
    50 pound Deadlift (pretty easy actually, but it is my first time doing a deadlift so I focused on form)

    50 pound shoulder press (OMG difficult. Did 21/9-fail/9. Tried to focus on form)

    So far my girlfriend has noticed a difference in the tone of my muscles. I assume it is because I am actually using them instead of letting them sit around all day. Great stuff so far.

    Started exercising again.

    And this time I following the Crossfit program. It focuses on real world power, not strength or how much weight you can sling around.

    Todays Workout of the Day(WoD) was:
    Three rounds for time of:
    50 Pull-ups
    185 pound Deadlift, 21 reps

    My personal goals however are this:
    Three rounds (untimed) of:
    5 pullups
    20 Tabata squats / box jumps

    Reality:
    Round one:
    2 full pullups, 3 jumped with slow negative
    20 Tabata squats

    Round two:
    1 full pullup, 4 jumped with slow negative
    20 18″ box jumps (there was a bench nearby)

    Round three:
    1 full pullup, 4 jumped with slow negative
    20 Tabata squats

    Results: My shoulders/arms are killing me and I can hardly walk. It’s Crossfit baby!

    It is scientific!

    I swear it is! On my robot dollar!

    NerdTests.com says I'm a Cool Nerd God.  What are you?  Click here!

    I hope Google bids on the 700mhz spectrum

    It is time to shake up the Telco/wireless industry.

    Various telcos have mentioned how they want to charge companies like Google because they are making money off their networks.

    Google takes that threat seriously. Hopefully seriously enough that they take their $12 billion dollars and buy a national slice of the 700mhz spectrum. They already own thousands of miles of dark fiber across the US, so why not use the 700mhz band for the “last mile” transit to customers. Google will have a direct path to the customer and own every step of it. They could offer reduced rate/ad support cell phone and internet use.

    Now some people are scared of a situation like this, one company that owns the content, the transport and the devices you use to access the content. However, do you think GOOG could do any worse than AT&T already has? I mean they have already shown that they are will to work with the NSA to spy on American Citizens, it is awfully hard to beat that.

    I say we should give GOOG a chance and hope they outbid the others.

    Chess: Fun but filled with apprehension

    I have recently taken up chess again. I am finding it to be quite fun, but it also fills me with apprehension and doubt. When I log into my Gmail account and find some Move Notification emails from RedHotPawn, the first feeling I have is doubt. I have no idea why since it is just a casual game between friends (or internet strangers) and neither has anything to gain from the virtual conflict.

    Before I log in to check on the reported move, I find myself running through the game, trying to think if there was something I overlooked. A weed growing in a crack of my plan if you will. Once logged in,All the emotion I felt just melts away and are replaced with move analysis, plans, and counters. It is quite odd.

    I find myself having those feelings before other games too. In a multiplayer RTS game like Dawn of War, I go through that entire process before the game. Once in the game, again all the emotion drains away and is replaced with mechanical movements, plans, and defense. Could it be a coping mechanism when I am placed under stress? Or am I just afraid of getting beat down?

    Next Page »