#Name: Calum Macleod
#Date : November 6, 2012
#Purpose: A Python program with a loop that lets the user enter a series of whole numbers.
#The user should enter the number -99 to signal the end of series.
#After all the numbers have been entered,
#the program should display the largest and smallest numbers entered.
#The program should re-run as long as the user wants to work with another
#set of numbers.

import math

#Real number, square
#Real constant STOP = -99
STOP = -99

print( '''
------------------------------------------------------------------------------
Accept a number from the user and display the number and its square.
The program executes till the user enters -99.
Non-numberic input will be handled and an appropriate error message displayed.
Program will terminate when a non-numeric input is entered
------------------------------------------------------------------------------
''')
number = 1
while (number !=STOP):
    try:
        number = float(input("Please enter a number, %d to stop: " %STOP ))
        if (number != STOP):
            square = math.pow(number, 2)
    except ValueError:
        number = 1
        print("Non numberic data was entered.")
    except:
         print("Error with input...")
    else:
        if (number != STOP):
           square = math.pow (number, 2)
        print("The square of %.2f is %.2f." %(number,square))

print("Program terminating...")

I was wondering how i would get the largest and smallest number from any number that the user enters. Im about 4 weeks into my program but my teacher doesn't do a very well at explaining what to do.

Recommended Answers

All 11 Replies

compare number to saved smallest and biggest numbers and update accordingly. Why you need math.pow to do simple number * number and why do you need to do it twice? Test first this code is correct before expanding it further.

You keep track of the smallest and largest in separate fields. A little trick is to initialize both with the first input value since you don't know the range of the input numbers. For example, if you initialize largest to zero, thinking all numbers will be greater, someone could input negative numbers only.

import random

test_numbers= [random.randint(1, 20) for ctr in range(10)]
print "test_numbers =", test_numbers

largest=0
smallest=0
first_rec=True
for num in test_numbers:
    print num
    if first_rec:     ## initialize with first value input
        smallest = num
        largest = num
        print "begin with smallest and largest =", num
        first_rec=False
    if num < smallest:
        smallest = num
        print "smallest is now", smallest
    elif num > largest:
        largest = num
        print "     largest is now", largest

print "smallest =", smallest, "largest =", largest

And input is generally done something like the following as you can enter a word like "stop" to stop (note this from the instructions "Program will terminate when a non-numeric input is entered"). Plus, if someone wanted to enter -99 as a number, they could not in your original code.

number = 1
while (number.upper() != "STOP"):
    number = input('Please enter a number, or "stop" to stop: ' )
    if number.upper() != "STOP":
        try:
            num = float(number)
        except ValueError:
            print("Non numberic data was entered.")
        except:
             print("Error with input...")

You get the input, then determine if it is stop value or not, and then trigger an except if it is not a float.

Im not a very experienced programmer. My proffessor said that she wants it to stop when -99 entered and she makes things very complex and not very easy to understand for example using math.pow to do simple number * number. This was an example piece of code to help us do the assignment. Thanks for trying to help.

test_numbers= [random.randint(1, 20) for ctr in range(10)]

Can you explain what this does. Thank you.

minimum = None
maximum = None
while (number != "STOP"):
    number = input('Please enter a number, or "stop" to stop: ' )
    if number != "STOP":
        break

    try:
        num = float(number)
    except ValueError:
            print("Non numberic data was entered.")
    except:
            print("Error with input...")
    continue                            

    if (minimum) is None or (num < minimum):
        minimum = num

    if (maximum) is None or (num > maximum):
        maximum = num

print ("Maximum: ", maximum)
print ("Minimum: ", minimum)

I incorporated a few of your ideas and otherthings and was wondering why my maximum and minimum keep coming up with None instead of a number. when i execute the code.

You should be able to do simple debugging like adding print statements to test your code--all code has to be tested.

while (number != "STOP"):
    number = input('Please enter a number, or "stop" to stop: ' )
    if number != "STOP":
        print "breaking out of while loop," number, "not equal 'STOP'"
        break

and

try:
    num = float(number)
except ValueError:
        print("Non numberic data was entered.")
except:
        print("Error with input...")
print "before continue=this line executes no matter what was entered"
continue                            
print "after continue = calc max and min"

Post back with your solution as I think you are completely missing the logic here.

Ya im pretty lost

One approach would be to create a list of the numeric inputs and then use Python functions min and max to get the result. Here would be a typical example:

# create a list of integer/whole number inputs
mylist = []
while True:
    n = int(input("Enter a whole number (-99 to exit loop): "))
    if n == -99:
        break
    mylist.append(n)

# use max(mylist), min(mylist) functions
print("max number = {}".format(max(mylist)))
print("min number = {}".format(min(mylist)))

# additional test
print('-'*30)
print(mylist)

This is not a complete solution but should give you an idea of the program flow

minimum = None
maximum = None
while True:     ## infinite loop so use "break" to exit
        number = input('Please enter a number, or "stop" to stop: ' )
        if number in ["STOP", "stop"]:
            print "breaking while loop"
            break

        """ another way
        if number.isalpha() and number.upper() == "STOP":
            print "isalpha"
            break
        """

        try:
            num = float(number)
            if (minimum) is None or (num < minimum):
                minimum = num
            if (maximum) is None or (num > maximum):
                maximum = num
            print ("Maximum: ", maximum)
            print ("Minimum: ", minimum)

        except ValueError:
            print("Non numeric data was entered.")
        except:
            print("Error with input...")

print ("Final Maximum: ", maximum)
print ("Final Minimum: ", minimum)

using if- elif - else statement, create a python program that will input the hours and minutes in 24hrs format and output it in the 12 hr format

for example:

Enter Hours in 24 hr format:0
Enter Minutes in 24 hr format:21
12:21 AM

Enter Hours in 24 hr format:13
Enter Minutes in 24 hr format:55
1:55 PM

Enter Hours in 24 hr format:12
Enter Minutes in 24 hr format:60
Invalid Time

Majid, please do not hijack a thread with an unrelated question!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.