Why is code not printing the negative value in my list? The max value works fine but nothing prints for negative.
user_input = ''
user_values = []
x = 0
maxim = 0
sum = 0
avg = 0
neg_values = 0
mini = 0
while True:
user_input = (input('input:'))
if user_input in ['q', 'Q']:
break
elif user_input not in ['q', 'Q'] and user_input.isnumeric():
user_values.append(int(user_input))
for value in user_values:
maxim = max(value,maxim)
print( "the maximum value in the list is : " , maxim)
Minumum_value = min(user_values)
print( "the minumum value in the list is : " , Minumum_value)
for value in user_values:
if value < 0:
print("the negative values are : " , value)
The code should work as the user inputs value and quits when he types q
. Then it should find neg values or the max etc.
CodePudding user response:
This is not doing what you expect because isnumeric()
doesn't do what you think it does. Try this at a Python prompt:
>>> "-1".isnumeric()
False
To do what you want, convert the input value to int
and wrap the conversion in a try...except ValueError
.
try:
user_values.append(int(user_input))
except ValueError:
print("Invalid input", user_input, "ignored")
As a side note, this:
for value in user_values:
maxim = max(value,maxim)
is pointless. Instead do maxim = max(user_values)
. You only need to calculate the maximum once. Same for the minimum.
CodePudding user response:
This is due to your isnumeric
check: that isn't doing what you expect.
>>> '-3'.isnumeric()
False
The method checks is all characters are digits, the minus sign is not part of it.
You could use a try/except:
try:
user_values.append(int(user_input))
except ValueError:
print('invalid input')
CodePudding user response:
why don't you just use try-except?
while True:
user_input = (input('input:'))
if user_input in ['q', 'Q']:
break
elif user_input not in ['q', 'Q'] and user_input.isnumeric():
user_values.append(int(user_input))
Except Try this code.
while True:
user_input = (input('input:'))
if user_input in ['q', 'Q']:
break
else:
try:
user_values.append(int(user_input))
except ValueError:
print("Error log...")