理想情况下,我希望能够在确定饮品价格时提示用户输入“小”或“S”,“中”或“M”和“大”或“L”。这是所有不区分大小写的,所以“s”或“smaLL”是好的,等等。如果我输入一个'M',我得到一个索引代码超出范围的错误,它计算为一个小。一大片给了我一个媒介。帮助
print("Ie. 'S', 'M', 'L', 'Small', 'Medium, 'Large'" +
" or any variations in their letter case sensitivity will work.")
beverageSize = str(input("Input your desired size: "))
print("")
if len(beverageSize) > 1 and len(beverageSize) < 5:
exit(print("Error with choice of beverage input."))
elif beverageSize.startswith("S") or beverageSize.startswith("s") and\
beverageSize is beverageSize.isalpha() and len(beverageSize) == 0 or len(beverageSize) == 4 or\
beverageSize[0] == "S" or beverageSize[0] == "s" and\
beverageSize[1] == "M" or beverageSize[1] == "m" or beverageSize[1] == "" and\
beverageSize[2] == "A" or beverageSize[2] == "a" or beverageSize[2] == "" and\
beverageSize[3] == "L" or beverageSize[3] == "l" or beverageSize[3] == "" and\
beverageSize[4] == "L" or beverageSize[4] == "l" or beverageSize[4] == "" and\
len(beverageSize) != 5:
beverageSize = SMALL_SIZE
print("SMALl")
elif beverageSize.startswith("M") or beverageSize.startswith("m") and\
beverageSize is beverageSize.isalpha() and\ len(beverageSize) == 0 or len(beverageSize) == 5 or \
beverageSize[0] == "M" or beverageSize[0] == "m" and\
beverageSize[1] == "E" or beverageSize[1] == "e" or beverageSize[1] == "" and\
beverageSize[2] == "D" or beverageSize[3] == "d" or beverageSize[3] == "" and\
beverageSize[3] == "I" or beverageSize[3] == "i" or beverageSize[3] == "" and\
beverageSize[4] == "U" or beverageSize[4] == "u" or beverageSize[4] == "" and\
beverageSize[5] == "M" or beverageSize[5] == "m" or beverageSize[5] == "":
beverageSize = MEDIUM_SIZE
print("MEDIUM")
答案 0 :(得分:2)
在python中有更智能的方法来测试变量的值。使用if-else
条件的一种方法在评论中已经suggested。这是使用dict
:
size_dict = {'s' : SMALL_SIZE, 'small' : SMALL_SIZE,
'm' : MEDIUM_SIZE,'medium' : MEDIUM_SIZE,
'l' : LARGE_SIZE, 'large' : LARGE_SIZE}
beverageSize = size_dict.get(beverageSize.lower(), 'Invalid Size')
这使用dict.get
提取与您的输入相关联的值。如果用户在词典中输入了不存在的单词作为键,则为beverageSize
分配值Invalid Size
。
答案 1 :(得分:0)
首先,你的程序将不起作用,因为对于允许的值,这将永远是正确的:
if len(beverageSize) > 1 and len(beverageSize) < 5:
exit(print("Error with choice of beverage input."))
然后,在比较一下之前,先让自己休息并避免所有的大/小写检查:
bevarageSize = bevarageSize.lower()
现在开始比较:
if (beverageSize == 's' or bevarageSize == 'small'):
print 'small'
elif (beverageSize == 'm' or bevarageSize == 'medium'):
print 'medium'
elif (beverageSize == 'l' or bevarageSize == 'large'):
print 'large'
甚至更好,使用真正的Python风格:
if (beverageSize in ('s', 'small')):
print 'small'
elif (beverageSize in ('m', 'medium')):
print 'medium'
elif (beverageSize in ('l', 'large')):
print 'large'