I don't understand why this doesn't work. I want to print the highest negative value from a series of user-inputted negative ints. E.g., user inputs: -1, -5, -3, program returns -1. But my program (below) is returning -5. Why is this? Is my code totally messed up? I know I can use a list and max way around it but I don't want to over-complicate the program.
x = 0
done = False
while not done:
y = int(input("Enter another number (0 to end): "))
num = y
if num != 0:
if num < x:
x = num
else:
done = True
print(str(x))
Your operator should be greater than >
, not less than <
in order to take the maximum value. Initializing to -float('inf')
ensures the first negative value passes the condition:
x = -float('inf')
while True:
num = int(input("Enter another number (0 to end): "))
if num != 0:
if num > x:
x = num
else:
break
print(x)
You can drop the done
variable by using a while True...break
instead.
I know I can use a list and max way around it but I don't want to over-complicate the program.
You can do this in a single line using iter
with your sentinel 0
to call input
repeatedly, collecting an iterable of negative numbers. map(int, ...)
converts the iterable items to ints while max
returns the maximum:
max(map(int, iter(input, '0')))
Demo:
>>> m = max(map(int, iter(input, '0')))
-3
-1
-4
-2
0
>>> m
-1