[Tutor] Going Loopy over Loops

Gregor Lingl glingl@aon.at
Thu, 15 Aug 2002 08:57:46 +0200


Billie schrieb:

> Hello:
> I'm using Win95 and Python version 2.2. I'm new to Python and programming.
>  
> I'm having trouble understanding how loops work, especially when they 
> contain conditional statements. 


If you want to understand, how this works, put it in an extra file,
(replace imput by input)

>         radius = imput("Enter radius of circle: ")
>         while radius <= 0:
>             print "The number  entered must be positive."
>             radius = imput("Enter radius of circle: ")

Add some print statements to inform you whats going on, e.g.:

radius = input("Enter radius of circle: ")
while radius <= 0:
   
    print "while-loop entered, because radius =", radius
    print "hence condition radius <=0 is true"

    print "The number  entered must be positive."
    radius = input("Enter radius of circle: ")

print "while-loop exited, because radius =", radius
print "hence condition radius <=0 is false"

And run it. Example:

 >>>
Enter radius of circle: -4
while-loop entered, because radius = -4
hence condition radius <=0 is true
The number  entered must be positive.
Enter radius of circle: -100.9
while-loop entered, because radius = -100.9
hence condition radius <=0 is true
The number  entered must be positive.
Enter radius of circle: 0.02
while-loop exited, because radius = 0.02
hence condition radius <=0 is false

 >>>

Do it yourself now! If you unterstand what's going
on, return to your program.

You made the clever observation, that this part of the code
occurs several times in your program. So you developed
the desire to isolate it in a function:

>         l ==input("Enter length: ")
>         while l <= 0:
>             print "The number must be positive."
>             l = input("Enter length: ")


def getPositiveNumber():
        l ==input("Enter length: ")
        while l <= 0:
            print "The number must be positive."
            l = input("Enter length: ")

To make this work, you have to:

     add a statement, which outputs the resulting value of l,
     that is, as you used it with your area-functions,
     a return-statement

and you should provide a parameter for the promt of the
input-statement, because this changes every time you want
to use the function:
Perhaps it would also be nice to change then name of the
variable  l to something neutral, e.g. number

def getPositiveNumber(prompt):
        number==input(prompt)
        ...... etc. (while-loop here)
        return number

After you have managed this you may use
the function in the following way:

w = getPositiveNumber("Enter width: ")

etc.

Seems hard? Not so much! Try it!

Gregor