对于一件作业,一部分代码涉及要求用户在3个输入之间进行选择。为了确保代码可以接受任何格式的选项,我使用了.lower(),如下所示。
while True:
RequestTea = input("What tea would you like? English Breakfast, Green Tea or Earl Grey? ").lower()
if RequestTea.lower() not in ('earl grey','english breakfast','green tea'):
print("We do not offer that unfortunately, please choose again.")
else:
break
为了确认用户选择,我根据值使用了三种不同的打印件,
if RequestTea == 'earl grey':
print("Earl Grey Tea selected!")
if RequestTea == 'green tea':
print("Green Tea selected!")
if RequestTea == 'english breakfast':
print("English Breakfast Tea selected!")
为了减少这两行代码,我尝试将其打印('RequestTea',“选中”)但是我希望茶叶名称以大写的第一个字母显示,输入是。降低()。 我想将茶名(Request Tea)显示为标题,然后将“选中”显示为小写。
非常感谢。
答案 0 :(得分:0)
offered_tea = ('earl grey', 'english breakfast', 'green tea')
while True:
RequestTea = input("What tea would you like? English Breakfast, Green Tea or Earl Grey? ").lower()
if RequestTea in offered_tea:
print('{} selected!'.format(RequestTea.title()))
else:
print("We do not offer that unfortunately, please choose again.")
出:
What tea would you like? English Breakfast, Green Tea or Earl Grey? earl grey
Earl Grey selected!
答案 1 :(得分:0)
在print语句中还有另一种方法:
offered_tea = ('earl grey', 'english breakfast', 'green tea')
while True:
RequestTea = input("What tea would you like? English Breakfast, Green Tea or Earl Grey? ")
RequestTea_Lower = RequestTea.lower()
if RequestTea_Lower in offered_tea:
print(RequestTea_Lower.title(),' selected!')
else:
print("We do not offer that unfortunately, please choose again.")