Mismatch Error in Python even with perfect Output - python

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.

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')

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))

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)

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)

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)

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)

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)

Related

Loop and iteration question that iterates the wrong

I am trying to find the largest input number (see problem), but I get an error instead.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if (num == "done"):
break
try:
int(num)
except:
print("Invalid input")
continue
if largest == None or int(num) > largest:
largest = num
elif smallest == None or int(num) < smallest:
smallest = num
print("Maximum is", largest)
print("Minimum is", smallest)
For example, when entering 33 then 8, I see
Traceback (most recent call last):
File "/home/td/tmp/g/test.py", line 16, in <module>
if largest == None or int(num) > largest:
TypeError: '>' not supported between instances of 'int' and 'str'
num is the original input string. When you save it to largest or smallest, its still a string, not an integer. In the next round, you then try to compare one to int(num). But str and int can't be compared, hence the error. To fix, just remember that first conversion of str to int and use that value later on.
As a side note, None is one of the very few times that comparing with is is better than comparing with None. None is guaranteed to be a singleton so is always works. Although its safe with int, not all custom classes that override __eq__ remember to test for None.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if (num == "done"):
break
try:
num = int(num)
except:
print("Invalid input")
continue
if largest is None or num > largest:
largest = num
elif smallest is None or num < smallest:
smallest = num
print("Maximum is", largest)
print("Minimum is", smallest)

Why is my code not displaying the correct max when I type in "bob" in between other numbers?

largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print(num)
if smallest is None :
smallest = num
elif num < smallest :
smallest = num
print(smallest, num)
if largest is None:
largest = num
elif num > largest:
largest = num
print(largest, num)
except:
print("Invalid input")
continue
print('Max', largest)
print("Minimum", smallest)
Asked to find the largest and smallest number from the input but if you type in a non number it mistakes that as the max value instead of calling it a "invalid input". Help?
It has to do with the fact that the value of "num" is being treated like a string. If you want to trigger an error exception refer to a revised version of your code with the attempted population of a numeric variable.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print(num)
x = int(num) # Add this in to force an error exception
if smallest is None :
smallest = num
elif num < smallest :
smallest = num
print("Smallest:", smallest, num)
if largest is None:
largest = num
elif num > largest:
largest = num
print("Largest:", largest, num)
except:
print("Invalid input")
continue
print('Max', largest)
print("Minimum", smallest)
That should provide the error condition you are after.
The problem is that you are trying to compare strings, instead of integers. When you compare strings, Python uses lexical order to compare them.
print("100" < "2") # Prints "True", because "1" is lower than "2" in lexical order
If you compare integers instead, then Python will use numerical order, which is what you expect here.
print(100 < 2) # Prints "False", because 100 is greater than 2
To fix this, you can convert your input to a integer before comparing it. This should be done after checking whether the input equals "done", because "done" cannot be converted to an integer.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print(num)
num = int(num)
if smallest is None :
smallest = num
elif num < smallest :
smallest = num
print(smallest, num)
if largest is None:
largest = num
elif num > largest:
largest = num
print(largest, num)
except:
print("Invalid input")
continue
print('Max', largest)
print("Minimum", smallest)
Also, if you want to allow fractional numbers like 1.2, then you can use float instead of int.
num = float(num)
You should specify the type of exception you're looking for, and limit the window the exception can occur in as much as possible, this helps with trying to debug situations like this:
largest = None
smallest = None
while (num := input("Enter a number: ")) != 'done':
try:
num = float(num)
except ValueError:
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('Max:', largest)
print("Minimum:", smallest)

How do I avoid unwanted assignment in loops when using comparison operators?

This is my code which iterates and takes inputs as the number and when user input "done", it comes out of loop and print smallest and largest of the input numbers.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
a = int(num)
except:
print("Invalid input")
if largest is None:
largest = num
if smallest is None:
smallest = num
if smallest > num:
smallest = num
if largest < num:
largest = num
print(smallest, largest) #for dry run
print("Maximum is", largest)
print("Minimum is", smallest)
Now my problem is whenever I input a non-number such as bob, it gets assigned to largest and print maximum number as bob.
You are acknowledging that int(num) failed, but then using the value of num (rather than a) anyway. You could continue the loop instead. With correct indentation, your code should look something like
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
a = int(num)
except ValueError:
print("Invalid input")
continue
if largest is None:
largest = a
if smallest is None:
smallest = a
if smallest > a:
smallest = a
if largest < a:
largest = a
print(smallest, largest) #for dry run
print("Maximum is", largest)
print("Minimum is", smallest)

Intro to Python HW assignment

Instructions: 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.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num = int(num)
except:
print('Invalid input')
continue
if smallest is None or num < smallest :
smallest = num
elif largest is None or num > largest :
largest = num
print("Maximum is", largest)
print("Minimum is", smallest)
So after inputting 7, 2, bob, 10, and 4, and then entering done, the code will not print out the max and min numbers as I have coded in the last two lines. Where is my mistake?
Thanks
You can append the numbers to a list and use built-in methods to do that for you, min() and max(). For example:
my_list = []
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num = int(num)
my_list.append(num)
except:
print('Invalid input')
continue
largest = max(my_list)
smallest = min(my_list)
print("Maximum is", largest)
print("Minimum is", smallest)
It will not work in a case where the largest integer is the first input. You could try to initialize the largest and smallest variable to the first input to solve it.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num = int(num)
except:
print('Invalid input')
continue
if largest is None:
largest,smallest = num,num
elif num < smallest :
smallest = num
elif num > largest :
largest = num
print("Maximum is", largest)
print("Minimum is", smallest)

PYTHON: Can't store value in variable, stays None

I'm trying to write this program which asks for numbers and stores the smallest and largest in two variables which are both None at the beginning.
Somehow the largest number is stored as I want it but the smallest number never makes it.
Here's my code:
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
except :
print "Invalid input"
continue
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
print "Maximum is", largest
print "Minimum is", smallest
As soon as I typed in some numbers and end the program with "done" the output looks like this:
Maximum is 56
Minimum is None
I checked the indentation a couple of times.
Don't you mean :
if smallest is None or num < smallest :
smallest = num
if largest is None or num > largest :
largest = num
instead of :
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
Because nothing is ever stored in smallest nor largest in the code you posted and as pointed by #MartijnPieters None is always smaller than numbers in python 2.
You can check this link : Is everything greater than None? for further information on that subject.
Also I'd prefer using explicit except such as except ValueError: in you case rather than something that catches everything.
Largest and smallest are never assigned to.
And in the spirit of writing pythonically, you can use min and max :)
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
a.append(num)
except :
print "Invalid input"
continue
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print "Maximum is", largest
print "Minimum is", smallest
You can replace the for loop with smallest=min(a)
#d6bels Answer is correct, but you need to add:
if smallest == None:
smallest = num
if largest == None:
largest = num
all code applied:
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done": break
try:
num = int(inp)
a.append(num)
except:
print("Invalid input")#For the sake of 2.x-3.x compatability, format your
if smallest == None: #prints as a function
smallest = num
if largest == None:
largest = num
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print("Maximum is " + str(largest))
print("Minimum is " + str(smallest))

Categories

Resources