I was presented with this question as part of my Intro to Prog & Logic class.
Problem 5: Write a simple program that the user can enter any number of positive and negative integer values and display the total number of positive values entered and the total number of negative values entered. We are going to use a sentinel value to control the loop. If the user wants to quit counting positive and negative numbers, the user will enter 'q'. The first line should display a title that says something like "Problem 5: Counting the number of positive and negative values entered by the user".
The trouble I am having is getting q to stop the loop. My professor does not like us using breaks (he takes points off every time you do) so thats where the trouble is coming in.
This is my code so far:
count_pos = 0
count_neg = 0
n = int(input('Enter the first number'))
while n != 'q':
if n > 0:
count_pos += 1
elif n < 0:
count_neg += 1
n = int(input('Enter the next number'))
print('The number of positive values entered is: ',count_pos)
print('The number of negative values entered is: ',count_neg)
Everything goes well until I try to stop the program and then I get the error "ValueError: invalid literal for int() with base 10: 'q'" If i switch the sentinel value to 0 there are no issues.
Any help would be appreciated, thank you!
int(input())in this situation. Just useinput(), and only after you have verified that it wasn't 'q' should you applyint()to it.n = int(n)at the top of thewhileloop, perhaps - after you have compared the input to 'q', but before you do anything requiring the numeric value of the input.