[Tutor] figured it out

Michael Janssen Janssen at rz.uni-frankfurt.de
Fri Apr 23 06:18:51 EDT 2004


On Fri, 23 Apr 2004 Simonjthecat at aol.com wrote:

> Ok... with a little trial and error I figured it out by myself (yay!  this is
> my first working program!)

fine!

>I'll go ahead and put what I came up w/....  Is
> this the most efficient way?  It seemed kinda weird to define shape as the same
> thing twice but it works.

it's quite ok. Another possibility you will often see/use in code is to
start an infinite while-loop and "break" it later:

while 1: # loop forever
     shape = raw_input("Which shape[1,2,3,quit]? ")
     if shape == 'quit':
          # step out of the while loop
          break
     # further ifs and elses


Instead of keyword 'break' you can use sys.exit(), when you want to
terminate the whole programm.



Hey, your code contains a minor mistake that's might be useful for
learning. Rewrite the "elif shape == 'quit'" part this way:

    elif shape == 'quit':
         print "okey, got a 'quit' - now terminate programm"
         sys.exit()


and tell us why the text doesn't get printed out, when typing quit! What
happens instead?


Michael

> Here it is.
>
> import sys #for exit command
> shape = raw_input("Which shape[1,2,3,quit]? ")
>
> while shape != 'quit':
>    print """
>    Choose a shape from the list:
>    1) Triangle
>    2) Square
>    3) Circle
>    """
>    # 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
>
>    elif shape == 'quit':
>       sys.exit()
>
>    else:
>       print "Sorry, You didn't enter a valid choice"
>
>    shape = raw_input("Which shape[1,2,3,quit]? ")
>



More information about the Tutor mailing list