Sentinel loops in python

折月煮酒 提交于 2021-02-05 07:25:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!