Python 只允许用户输入某些单词
这不管用, 我想不出来。。。 我希望它打印错误语句或中断。。 我想试一试,但那不太好。 我是python新手:-)Python 只允许用户输入某些单词,python,Python,这不管用, 我想不出来。。。 我希望它打印错误语句或中断。。 我想试一试,但那不太好。 我是python新手:-) 为True时: unitFrom=输入(“输入温度单位,华氏、开尔文或摄氏:”) 列表=[“华氏”、“摄氏”、“开尔文”] 如果列表中的unitFrom.lower(): 打破 其他: 打印(“单位错误,请重试”) 打破 切勿使用内置关键字定义新变量 将列表置于循环之外,以避免在每次迭代时初始化它 由于要检查列表中的小写输入,因此需要使用小写形式的列表: 因此: x_units
为True时:
unitFrom=输入(“输入温度单位,华氏、开尔文或摄氏:”)
列表=[“华氏”、“摄氏”、“开尔文”]
如果列表中的unitFrom.lower():
打破
其他:
打印(“单位错误,请重试”)
打破
x_units = ["fahrenheit" , "celsius" , "kelvin"]
# or x_units = [x.lower() for x in x_units] if you do not wish to change the original list
while True:
unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:")
if unitFrom.lower() in x_units:
break
else:
print ("Wrong unit, try again")
break
要打印中断还是要执行中断? 和
list=[“华氏”、“摄氏”、“开尔文”]
每次都会新建
在之前执行它,而True:
并使用除list以外的其他内容作为数组名,因为list
是一个关键字
answer_list = ["Fahrenheit" , "Celsius" , "Kelvin"]
while True:
unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:")
if unitFrom.lower() in answer_list:
break
else:
print ("Wrong unit, try again")
break
问题是你没有使用小写单位。然后检查是否
“开尔文”==“开尔文”
,这永远不会为真
将单位列表替换为小写或仅使用以下代码:
while True:
unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:")
myList = ["Fahrenheit" , "Celsius" , "Kelvin"]
myList = [unit.lower() for unit in myList] #transform all strings inside list to lowercase
if unitFrom.lower() in myList:
break
else:
print ("Wrong unit, try again")
break
也不要使用list
作为变量名。正如@dirtybit所指出的,您应该注意这些点
设置访问速度比列表快,如果列表大,您可以尝试Set
与输入进行比较
解决方案:
units_set=set(“华氏”、“费尔斯”、“开尔文”)#仅初始化一次,小写值。
尽管如此:
unit_from=输入(“输入温度单位,华氏、开尔文或摄氏:”)
如果units\u集合中的units\u from.lower():
#在这里做点什么。
打破
其他:
打印(“单位错误,请重试”)
您可以试试这个
loopBool = True
while loopBool:
unitList = ["fahrenheit", "celsius", "kelvin"]
try:
unitFrom = raw_input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:")
if unitFrom in unitList:
inBool = True
if inBool == True:
print("Success")
loopBool = False
else:
raise Exception
except:
print ("Wrong unit, try again")
问题可能是您使用的input()函数
我不想将代码更改太多(在我的情况下,您应该考虑更低的代码)
您可以进一步了解它:不要使用关键字list
来定义列表,也不要使用内置声明来定义新变量。您应该将“list”更改为其他内容,因为list
本身就是一个内置函数。
while True:
unitFrom = raw_input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:")
unitList = ["Fahrenheit", "Celsius", "Kelvin"]
if unitFrom in unitList:
break
else:
print ("Wrong unit, try again")
break