Shubham Shekhar
Shubham Shekhar

Reputation: 189

Mismatch Error in Python even with perfect Output

I got this as my assignment:-

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.
Desired Output-
Invalid input
Maximum is 10
Minimum is 2

I wrote the following code for the same-

largest = None
smallest = None
count=0
while True:
    num = input("Enter a number: ")

    if num == "done" :
        break
    try:
        fval=float(num)
        count=count+1

        if(fval == None):
            largest=None
            smallest=None

        if(largest<fval):
            largest=int(fval)
        if(count==1):
            smallest=fval                    
        else:
            if(int(fval) < smallest):
                    smallest=int(fval)



    except:
        print("Invalid input")
        continue






print("Maximum is", largest)
print("Minumum is", smallest)

It is working fine too. I am able to fetch the smallest and largest entries. But, at the end, the editor is not accepting this code. Any possible error in the code logic?

Thanks for help in advance.

Upvotes: 1

Views: 8404

Answers (7)

Meg Webster Noah
Meg Webster Noah

Reputation: 1

largest = 0
smallest = 999999
inval = "notdone"
x = 0

while True :
    inval = input("Enter a number: ")
    if (inval == "done") :
        break
    else :
        try:
            x = int(inval)
            if (x > largest) :
                largest = x
            if (x < smallest) :
                smallest = x           
        except :
            print("Invalid input")  
    
print("Maximum is", largest)
print("Minimum is", smallest)

Upvotes: 0

largest = None smallest = None

while True: try: num = raw_input("Enter a number: ") if num == "done": break if largest is None: largest = int(num) if int(num) > largest: largest = int(num) if smallest is None: smallest = int(num) if int(num) < smallest: smallest = int(num) except: print ("Invalid input")

print("Maximum is", largest) print("Minimum is", smallest)

Upvotes: 0

Eyal Barzilay
Eyal Barzilay

Reputation: 1

largest = None
smallest = None

while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        n = int(num)
        if smallest is None or n < smallest:
            smallest = n
        if largest is None or n > largest:
            largest = n
    except ValueError:
    # num cannot be converted to an int
        print ("Invalid input")

print("Maximum is", largest)
print("Minimum is", smallest)

Upvotes: 0

Divya Prakash
Divya Prakash

Reputation: 61

The below code i wrote working fine in all the terminals, try this one it will work.

largest = None
smallest = None
cnt = 0
while True:
    num = input("Enter a number: ")
    if num == "done" : break

    elif(num == ""):
         print("InValid num")
         break
    try :
        val = int(num)
        #print(val)
        #break
    except ValueError:
        val = -1
        print("Invalid input")
        continue


    if cnt == 0 :
        largest = val
        smallest = val
    elif val > largest :
        largest = val
    elif val < smallest :
        smallest = val

    cnt = cnt +  1  




print("Maximum is",largest)
print("Minimum is",smallest)

Upvotes: 1

Richard Neumann
Richard Neumann

Reputation: 3361

Some advises:

  • Only put code in the try-block that you actually expect to raise the exception.
  • Do not do Pokemon Exception handling (Gotta catch 'em all). Only handle exceptions you actually expect.
  • Why do you (try to) convert the user input to float if you are requsted to check for integers?
  • float(num) will never be None, so checking for it does not make any sense.

Finally, I'd come up with:

if __name__ == '__main__':
    minimum = maximum = None

    while True:
        user_input = input('Enter a number: ')

        if user_input == 'done':
            break

        try:
            integer = int(user_input)
        except ValueError:
            print('Invalid input')
        else:
            if minimum is None or integer < minimum:
                minimum = integer

            if maximum is None or integer > maximum:
                maximum = integer

    print('Maximum is', maximum)
    print('Minimum is', minimum)

Upvotes: 1

N&#233;stor
N&#233;stor

Reputation: 351

I will use isinstance to check if the input is a integer and I will store all the elements in a listto, at the end of my program, call min and max.

Here's a code that works:

import ast

inputs = []
while True:
    num = input("Enter a number: ")

    if num == "done" :
        break
    try:
        # Check if the input is a number
        if num.isnumeric():
            # If so, convert the string to a number
            number = ast.literal_eval(num)
            # If it's an int, store it in the list
            if isinstance(number, int):
                inputs.append(number)
            else:
                # If not, raise and exception
                raise ValueError("Not an integer!")

    except ValueError as ve:
        print(ve)

# Show the desired output
print("Maximum is", max(inputs))
print("Minumum is", min(inputs))

Upvotes: 1

cs95
cs95

Reputation: 402263

I believe there is a mismatch between your version of python and the version that the code judge runs to evaluate your code.

What's the difference? None can be compared to integers (actually, almost everything is comparable in python2). Look at this:

Python 2.x

In [211]: None < 123456
Out[211]: True

Python 3.x

In [152]: None < 123456
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-152-cf9ae210e7ad> in <module>()
----> 1 None < 123456

TypeError: unorderable types: NoneType() < int()
> <ipython-input-152-cf9ae210e7ad>(1)<module>()
----> 1 None < 123456

How does that matter to you? Well, for the first iteration, this line of code:

if(largest < fval):

Will compare fval with largest, which has an initial value of None.

Just another note, be wary about input in python2 vs python3. The two behave differently. The former will throw a NameError when you type a string.


I would recommend initialising your largest and smallest to valid values, like this:

largest = float('-inf')
smallest = float('inf')

Upvotes: 3

Related Questions