Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try and Except Help
#1
I need your help.

I have edited the following code which I would like to do the following:

1. Continuously Prompt user to input until they enter "done". This works.
2. Once "done" is entered, print the largest and smallest of the numbers. Initially it does but what I would like is to be able to keep track of the earlier entries without having "largest" and "smallest" variables as I have. I would like the user to try to enter as many times, with me just printing the largest of those entries and the smallest.

Kindly asking for guidance.

My code is below:

largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == "done":
        largest = input("Enter Max")
        smallest = input("Enter Min")
        print("Maximum", largest)
        print("Minimum", smallest)
        break
    try:
        entryStuff = float(num)
    except:
        print("Invalid input")

print("Maximum", largest)
Reply
#2
indent:
print("Maximum", largest)
to same level as:
print("Invalid input")
Reply
#3
You have two things to deal with.
  • initialising the largest and smallest variables
  • check each input to see if larger/smaller and changing accordingly

The initialising is tricky as you either need to set them to:
  • -ve or +ve largest_number_possible_on_system for largest & smallest respectively, or
  • first number entered (better option) - using a list, or
  • None (as you have done) - but if you do this, you will need to check inside the loop if they are None every time

If you read all of the numbers first, into a list, then you could just initialise to the first number in the list and then check the rest. Incidentally, if you go with a list, you don't need to bother with largest and smallest variables as there are max and min functions you can apply to the list in print statements.

Alternatively, you could create a function that gets and validates user input. Call it once to set the initial values and then call it repeatedly in a loop, checking if the new value is higher or lower than your stored values (this is the key bit of work).

You are currently missing the key bit of work in the loop - namely what to do if you don't have a 'done' input and the number is cast to float correctly. You can either put the code under the cast (inside try:) as it will only execute if the float works OR you can put under an else: clause for the try/except block. I prefer the latter approach, but some prefer the former.
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020