Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with this code
#1
Can someone help me with this? I'm not sure what I have done wrong.

Exercise 5.2: Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.

smallest = None
largest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
if largest is None:
largest = num
elif num > largest:
largest = num
print("Maximum is", largest)
print("Minimum is", smallest)


This is what I got:
Invalid input
Maximum is 7 ← Mismatch
Minimum is 10

This is what I was supposed to get:
Invalid input
Maximum is 10
Minimum is 2
buran write Feb-08-2021, 04:08 PM:
Please, don't post screenshots. Copy/paste as code and traceback as text and use proper tags when post code, traceback, output, etc.
See BBcode help for more info.
Reply
#2
Please post your code and error trace, not a screenshot and definitely not a link.
buran likes this post
Reply
#3
Your code works as expected, at least as I expect. If I enter these values (5, 22, 311) I get the smallest is 22 and the largest is 5, and those are the correct values. Well, they are the correct values if you treat each number as a string, which you are doing. You probably want to use the result of this command:
fnum = float(num)
Your program is doing comparisons with "num", which is a string, not "fnum" which is a float number.

You can also compress you comparison a bit.
    if smallest is None:
        smallest = fnum   # You will set smallest and largest at the same time
        largest = fnum    # when None.  Make that obvious
    elif fnum < smallest: 
        smallest = fnum   # There will never be a number < smallest and > largest
    elif fnum > largest:
        largest = fnum
Reply
#4
Thank you! That helped a lot. I'm new to this and made a dumb mistake not using fnum.

Thanks again!
Reply


Forum Jump:

User Panel Messages

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