0

This is my try to 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. But it's false. I need some help can someone explain my fault.

largest = 0
smallest = 0



while True:
    num = input("Enter a number: ")
    if num =="done": break
    try:
           fnum = float(num)
    except:
        print("Invalid input")
        continue

    if largest == 0 or num >= largest: largest = num
    else: largest= largest
    if smallest == 0 or num <= smallest: smallest = num
    else: smallest= smallest

print("Maximum is", largest)
print("Minimum is", smallest)
2
  • Just Fyi we have min/max builtin functions in this language Commented Jun 28, 2020 at 22:51
  • i know but i really need to got this Commented Jun 28, 2020 at 22:54

2 Answers 2

1

Instead, why don't you a list to store the values, then you can use the min and max methods:

nums = []

while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        fnum = float(num)

    except:
        print("Invalid input")
        continue

    nums.append(fnum)

largest = max(nums)
smallest = min(nums)

print("Maximum is", largest)
print("Minimum is", smallest)
Sign up to request clarification or add additional context in comments.

Comments

0

You should be using fnum in those if statements, not num.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.