greatest and least of these...

Erik Jones erik at myemma.com
Tue Oct 23 19:10:13 CEST 2007


On Oct 23, 2007, at 10:56 AM, Shawn Minisall wrote:

> I just wrote a program to let the user input a series of whole numbers
> and tell them which is least and which is greatest based off of a  
> menu.
> However, the menu isn't kicking in after they pick a number.  I  
> included
> a while statement for a loop just for the menu and compared it to my
> other programs that have a similar setup and are working, but I'm
> stumped.   Here's the program...
>
> def main():
>
>     #define and initialize variables
>     #choice as int
>     choice = 0
>     #number as int
>     number = 0
>
>     #intro
>     print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!"
>     print
>
>     #Menu loop
>     while choice != 2:
>         #display menu
>         print "Please choose from the following menu: "
>         print "1. Enter a number"
>         print "2. Exit"
>         print
>
>         #prompt user for their menu choice
>         choice = input("Enter your choice here: ")
>
>         #if statements to determine which choice
>         if choice == 1:
>             nums = []
>             while number >=0:
>                 nums.append(number)
>                 number = input("Please enter a number.")

You're telling the script to continue asking for numbers until a non- 
positive number is entered.  Enter a negative number and you'll see  
your menu again.  What you probably want is to change this.

>
>
>         elif choice == 2:
>             print "Have a great day!"
>
>             if len(nums) > 0:
>                 print "The smallest number that you entered  
> was:",min(nums)
>                 print "The largest number that you entered was:",max 
> (nums)
>
>         else:
>             #invalid
>             print "Invalid selection.  Enter either one or two."
>             print
>
> Also, if they quit the program with choice #2 and entered numbers, it
> should display the greatest and least of them.  If they just  
> started and
> didn't enter anything and want to quit, I get an error message saying
> UnboundLocalError: local variable 'nums' referenced before assignment.
> Isn't the if statement supposed to keep python from going there  
> since if
> they didn't enter any input, the length of the list should just be  
> zero.

The exception is because you're not ensure that nums is ever  
initialized.

Erik Jones

Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com





More information about the Python-list mailing list