Shubham Shekhar Shubham Shekhar -3 years ago 183
Python Question

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
while True:
num = input("Enter a number: ")

if num == "done" :

if(fval == None):

if(int(fval) < smallest):

print("Invalid input")

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.

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download