问题
So I am getting inputs to store into a list from the user and I am using a sentinel loop to continuously ask the user to input a number. The issue that arises is when I use "Stop" to end the loop when the user is done inputting values I get an error which is
ValueError: invalid literal for int() with base 10: 'Stop'
I'm not sure why, if it is because it is inputting a string to end the while loop when the input is for ints. Any advice to get rid of this error is greatly appreciated thanks, and my code is below as well.
def getInput():
nums = []
print("Enter a value, to end the list, input Stop")
userInput = input("")
while userInput.upper() != "Stop":
print("Enter a value, to end the list, input Stop")
nums.append(int(userInput))
userInput = input("")
return nums
def main():
numbers = getInput()
print(numbers)
main()
回答1:
userInput.upper() != "Stop":
will always be True
: 'stop'.upper()
is 'STOP'
.
if you want your loop to terminate when the user enters any capitalized version of 'stop'
you should write
while userInput.upper() != "STOP":
....
and it may be sensible to catch other things a user could enter with
userIntput = input("")
try:
nums.append(int(userInput))
except ValueError:
# somehow handle what should happen here...
来源:https://stackoverflow.com/questions/54899568/sentinel-loops-in-python