Loop and iteration question that iterates the wrong - python

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)

Related

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)

I have a problem with arranging None and input data to find largest and smallest value using python

Edit: Here are the test values (7, 2, bob, 10, and 4) and desired output
Invalid input
Maximum is 10
Minimum is 2
for people who want them :)
Hello! So I got this problem where I have to take input from user and then when the type done the largest and smallest values come out. There was a small part where if you put wrong data it will tell you that but I got that "done" perfectly. But the part where I have to decide as largest and smallest is my issue. I setup Nonetype for each of the values but when i put it in the if statements it simply selects the first input as largest. I have attached my code below. Any modification could be of help. Thank you.
Largest = None
Smallest = None
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
fnum = int(num)
except :
print("Invalid input")
continue
if Largest is None:
Largest = fnum
elif Smallest is None:
Smallest = fnum
elif fnum > Largest:
fnum = Largest
elif fnum < Smallest:
fnum = Smallest
print("Maximum is",Largest)
print("Minimum is",Smallest)
Ideally, you can go with == (equals to) for the comparison between None
x = None
y = None
print(x is y)
print(x==y)
prints
True
True
Now, you have all the conditions as if and elif, so every time in the first iteration the Largest is assigned (because that is the first True condition) and in the second iteration Smallest is assigned (because that is the second True condition) and this logic may not be the case always.
What you can do is, set the largest and smallest at the same time, i.e have the same reference point before the comparison.
Finally, you are not updating the smallest and the largest but doing it reverse (as pointed out in the comments).
Stitching it all together,
Largest = None
Smallest = None
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
fnum = int(num)
except :
print("Invalid input")
continue
if Largest == None or Smallest == None:
Largest = fnum
Smallest = fnum
elif fnum > Largest:
Largest = fnum
elif fnum < Smallest:
Smallest = fnum
print("Maximum is",Largest)
print("Minimum is",Smallest)
If you want to keep the Largest and Smallest as None you could perform a conditional expression to assign the values. This would result the first value being assigned to both Largest and Smallest and then only to Smallest of Largest if the value is bigger or smaller.
This is not the most optimized way to do this but it gets the job done.
Largest = None
Smallest = None
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
fnum = int(num)
except :
print("Invalid input")
continue
Largest = fnum if Largest is None else fnum if fnum > Largest else Largest
Smallest = fnum if Smallest is None else fnum if fnum < Smallest else Smallest
print("Maximum is", Largest)
print("Minimum is", Smallest)
Output with single number.
Output with your numbers.
There is so many ways that you can do this. You should try using an array.
First, you create an array which will store all the numbers. If the user type "done", you store the maximun and the minimun number for the array in two variables. Really simple.
numbers = []
while True :
num = input("Enter a number: ")
if num == "done" :
break
try:
num = int(num)
numbers.append(num)
except:
print("Invalid input")
continue
Largest = max(numbers)
Smallest = min(numbers)
print("Maximum is", Largest)
print("Minimum is", 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)

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

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)

Categories

Resources