#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2004
    Posts
    1
    Rep Power
    0

    First Post, Simple Python Question (nooblike)


    Hello out there! Just wanted to introduce myself to Dev Shed... I must say this seems like an excellent community!

    I'll get right down to business. I'm currently in the process of learning Python which is my first programming language and my first exposure to anything other than old DOS .bat files. After just getting into Linux I decided that I need to learn some coding skills. Maybe I should be learning C or C++ right now but Python was the language that I found a bunch of tutorials that seemed to be basic enough for me to suss out in my spare time.

    Here's the code I was given to start in an exercise in one of my tutorials. Bear with me, I know this is ultra ultra simple stuff...

    Code:
    #################################
    # Note use of triple quoted string to make a menu
    print """
    Choose a shape from the list:
    1) Triangle
    2) Square
    3) Circle
    """
    
    shape = raw_input("Which shape[1,2,3]? ")
    
    # note must now test for character '1' not 
    # number 1 coz raw_input returns strings not numbers
    
    if shape == '1':     # a triangle
       ht = input('What is the height of your triangle? ')
       base = input('How long is the base? ')
       print "The triangle's area is: ", 0.5*base*ht
    
    elif shape == '2':   # square
       side = input("How long are the square's sides? ")
       print "The square's area is: ", side*side
    
    elif shape == '3':   # a circle 
       rad = input('What radius is your circle? ')
       print "The circle's area is: ", 3.14159*rad*rad
    
    else:
       print "Sorry, You didn't enter a valid choice"
    The goal of the exercise was to add a 4th quit option to the program and to keep the program looping until the quit option was chosen. I've managed to satisfy those conditions and I just wanted some of you more experienced people to tell me if I went about solving this problem in the most efficient way. I'm COMPLETELY open to constructive criticism. In fact, thats exactly what I'm looking for! Here's what I modified.

    Code:
    #################################
    # Note use of triple quoted string to make a menu
    print """
    Choose an option (number) from the list:
    1) Triangle
    2) Square
    3) Circle
    4) Quit
    """
    
    shape = raw_input("Which option[1,2,3,4]? ")
    
    # note must now test for character '1' not 
    # number 1 coz raw_input returns strings not numbers
    
    
    #Originally intended to have shape = 4 change this value but i found it easier to
    #call a sys.exit()
    
    loopervar = 0          
    while loopervar <=0:     
        if shape == '1':    
           ht = input('What is the height of your triangle? ')
           base = input('How long is the base? ')
           print "The triangle's area is: ", 0.5*base*ht
           print """
           Choose an option (number from the list:
           1) Triangle
           2) Square
           3) Circle
           4) Quit"""
           shape = raw_input("Which option[1,2,3,4]? ")
        
    
        elif shape == '2':   # square
           side = input("How long are the square's sides? ")
           print "The square's area is: ", side*side
           print """
           Choose an option (number from the list:
           1) Triangle
           2) Square
           3) Circle
           4) Quit"""
           shape = raw_input("Which option[1,2,3,4]? ")
    
        elif shape == '3':   # a circle 
           rad = input('What radius is your circle? ')
           print "The circle's area is: ", 3.14159*rad*rad
           print """
           Choose an option (number from the list:
           1) Triangle
           2) Square
           3) Circle
           4) Quit"""
           shape = raw_input("Which option[1,2,3,4]? ")
    
        elif shape == '4': #exit command
            import sys
            sys.exit()
    
        else:        # Line to keep prog from crashing out if unacceptable input
           print "Sorry, You didn't enter a valid choice"
           print """
           Choose an option (number from the list:
           1) Triangle
           2) Square
           3) Circle
           4) Quit"""
           shape = raw_input("Which option[1,2,3,4]? ")
    I guess my main question is whether I was correct in adding the """choose an option..." string to every shape condition.

    Thanks in advance for any replies!
    James
  2. #2
  3. Retired Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2004
    Location
    London, UK
    Posts
    6,669
    Rep Power
    147
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    It is not a good idea to duplicate code like that - if you decide to add a new option then you will need to change the print statement in several places.

    Instead, you can put the print and raw_input statements at the start of the loop, like this:

    Code:
    loopervar = 0          
    while loopervar <=0:     
        print """
        Choose an option (number from the list:
        1) Triangle
        2) Square
        3) Circle
        4) Quit"""
        shape = raw_input("Which option[1,2,3,4]? ")
    
        if shape == '1':    
           ht = input('What is the height of your triangle? ')
           base = input('How long is the base? ')
           print "The triangle's area is: ", 0.5*base*ht
        
    
        elif shape == '2':   # square
           side = input("How long are the square's sides? ")
           print "The square's area is: ", side*side
    
        elif shape == '3':   # a circle 
           rad = input('What radius is your circle? ')
           print "The circle's area is: ", 3.14159*rad*rad
    
        elif shape == '4': #exit command
            import sys
            sys.exit()
    
        else:        # Line to keep prog from crashing out if unacceptable input
           print "Sorry, You didn't enter a valid choice"
    It is also bad form to call sys.exit() to end the program, except under terminal error conditions. It is more elegant to end the loop and let the flow of control reach the end of the program. You can do this several ways -

    1) use the break statement to exit the loop like this

    Code:
    loopervar = 0          
    while loopervar <=0:     
        ....
        elif shape == '4': #exit command
            break
    2) change the value of loopervar so that the condition of the while statement is no longer true. In the code you give this would mean setting it to a number greater than zero, but it is clearer to use the values True and False:
    Code:
    loopervar = True
    while loopervar:     
        ....
        elif shape == '4': #exit command
            loopervar = False
    Hope this helps

    Dave - The Developers' Coach
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2004
    Location
    Belgium
    Posts
    3
    Rep Power
    0
    What did you want to do with loopervar? I didn't saw it could change in the code and still you check it for each iteration of your loop. You could use instead a fixed value, like True (or 1), and the your program would be in an ifinite loop. Untill python reads 'break' and then exits the loop, of course. Thus you avoid wasting ressources to create a variable and a repetitive check of the same variable.
    I would avoid such loops for complex code, however, since a program could virtually loop forever due to a innocent looking piece of code.

    The use of the break statements would also let you put some code after the loop to "clean up". Well, not here, but in a real program, why not?

    Here is how the code looks after those slight modifications:

    Code:
    while True:              #infinite loop
        print """
        Choose an option (number from the list:
        1) Triangle
        2) Square
        3) Circle
        4) Quit"""
        shape = raw_input("Which option[1,2,3,4]? ")
    
        if shape == '1':
           ht = input('What is the height of your triangle? ')
           base = input('How long is the base? ')
           print "The triangle's area is: ", 0.5*base*ht
        
    
        elif shape == '2':   # square
           side = input("How long are the square's sides? ")
           print "The square's area is: ", side*side
    
        elif shape == '3':   # a circle
           rad = input('What radius is your circle? ')
           print "The circle's area is: ", 3.14159*rad*rad
    
        elif shape == '4':   # exit command
           break             # here is the only exit.
                             # users should *always* know        
                             # how to get here.
    
        else:        #                                                    
           print "Sorry, You didn't enter a valid choice \n\n"
    
    # don't forget "\n"s (newlines) to format your text :)
    # these don't work with windows or macos, if I remember well.
    
    import sys               # if you insist ;)
    sys.exit(0)              # 0 means no problem encountered
    Your long list of "if foo == 'bar' " could be a switch/case-like statement, like the ones you can see here: http://simon.incutio.com/archive/2004/05/07/switch
    (but you have to know dictionnaries a bit here.)

IMN logo majestic logo threadwatch logo seochat tools logo