I am writing a program using while loop to determine the highest and lowest of a user's inputted numbers, allowing the user to enter as many numbers as they wish, before using the sentinel value of -1 to exit. Then, the program should print the lowest and the highest inputted values. My problem is, the sentinel value keeps entering the loop as an input value and is being considered part of the range. If the user does not enter a number below my sentinel value of -1, then the sentinel value is what appears as the lowest. I've spent time trying to fix it but without success. Does anyone have any ideas as to why this is happening and what should be done to mend it? Here is my code:
minimum = int()
highest = int()
while(True):
num = int(input("Enter a Number (Use -1 to Stop): " ))
if highest < num:
highest = num
if minimum > num:
minimum = num
if(num == -1):
break
print("The interval is",minimum,"-", highest)
Move lines 9 and 10 above line 5.
If you enter not a number, it will raise a
ValueError
.
If you enter for example
abc,
int
can't convert this to an integer.
Catch the
ValueError
Ask the user to use q or Q to quit the program.
# usually it's not good to
# set a name to None
# and afterwards to an integer
minimum = None # not set yet
maximum = None # not set yet
# if you forget this, you'll run
# into a TypeError, happens for example with comparison < or >
while True: # <- no parenthesis needed
user_input = input("Enter a Number (q|Q to quit): ")
if user_input.lower() == 'q':
break
try:
num = int(user_input)
except ValueError:
print(user_input, 'is not a valid integer')
# ask again for user input
continue
if minimum is None:
# the first time minimum and maximum
# is None
# Just setting minimum
# and maximum to the first user input
# this this will never again executed
minimum = num
maximum = num
# the code afterwards will be executed
# but does no change to the value
if maximum < num:
maximum = num
if minimum > num:
minimum = num
# fancy format string: Python 3.6+
# first minimum and maximum is equal
print(f"The interval is {minimum} -> {maximum}")
print('Program ends here')
Another approach would be use list and built-in min(), max() functions. With Python 3.8 walrus operator one can write:
answers = []
while (answer := input('Enter a number (q|Q) to quit): ').lower()) != 'q':
try:
answers.append(int(answer))
except ValueError:
print(f'Expected integer but got {answer!r}')
if answers:
print(f'Mininum value {min(answers)} and maximum value {max(answers)}')
else:
print('No integers entered!')