[Tutor] use while loop
denis
denis.spir at free.fr
Fri Apr 23 06:29:09 EDT 2004
----- Original Message -----
From: <Simonjthecat at aol.com>
To: <tutor at python.org>
Sent: Friday, April 23, 2004 5:13 AM
Subject: [Tutor] use while loop
> Ok. I know this is really simple, but it's my first program so anybody
can
> pobably answer it for me. This program finds the area of different
shapes.
> Right now, however, it only goes through one time and then exits the
program. I
> want to put it in a loop so that after one area is given it will start
over
> and ask what shape you want again. I figured out how to put it in a for
loop
> and get it to execute a given number of times. I'm assuming I need it in
a
> while loop but just can't do it. So anyway, here's what I've got so far.
(Nobody else answers ? I'll try to be clear...)
This is the typical case where a code section has to be executed once, and
only then a condition will tell if it should be repeted or not. In
pseudo-code it looks like :
loop
<instruction_bloc>
until exit_condition
or :
loop
<instruction_bloc>
while continue_condition
(where each condition is the logical negation (logical NOT) of the other
one.)
As python doesn't provide such a loop form with an end test, you need to use
the one you've got -- that is : the 'while' loop with a start test. And use
a double trick to transform it into what you want do :
while True : # (1) switch off start test
<instruction_bloc>
if exit_condition : break # (2) handmade end test
> import sys #for exit command
>
> print """
> Choose a shape from the list:
> 1) Triangle
> 2) Square
> 3) Circle
> """
> shape = raw_input("Which shape[1,2,3,quit]? ")
>
> # 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"
Either to simplify your loop or (logical inclusive OR) for trainig purpose,
you may put your area calculations into functions.
> I know this has a real simple fix.
> Thanx for the help
>
> Simon the Cat
>
----------------------------------------------------------------------------
----
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list