Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查输入是否为字母';l'';h';或';c';_Python_Python 3.x - Fatal编程技术网

Python 如何检查输入是否为字母';l'';h';或';c';

Python 如何检查输入是否为字母';l'';h';或';c';,python,python-3.x,Python,Python 3.x,我是编程新手,所以对我放松点。 我在理解这种if语句和while循环时遇到问题: command = input() if command != "l" or command != "h" or command != "c" print("Please insert l, h or c: ") command = str(input("l, h or c: ")) else: print("working") 我不明白为什么没有检查'h'或'c'。当我在IDE上尝试此功

我是编程新手,所以对我放松点。 我在理解这种if语句和while循环时遇到问题:

command = input()
if command != "l" or command != "h" or command != "c"
    print("Please insert l, h or c: ")
    command = str(input("l, h or c: "))
else:
    print("working")
我不明白为什么没有检查
'h'
'c'
。当我在IDE上尝试此功能时,我得到:

l
Please insert l, h, or c: 
l, h or c: 

你把布尔逻辑搞混了

如果
命令
l
,则它不等于
h
c
;这使得您的
if
语句为真:

False (!= l) or True (!= h) or True (!= c) == True
当两个选项中的一个为真时,
为真,并且对于您的测试,三个选项中至少有两个始终为真,可能是三个

您想改用

if command != "l" and command != "h" and command != "c":
或在3上使用
not
,或使用
=
相等的测试:

if not (command == "l" or command == "h" or command == "c"):
或者,使用
not in
对一组选项进行测试,效果更好,可读性更好:

if command not in {'l', 'h', 'c'}:
您可以尝试以下方法:

command = input()
if command not in {'l','h','c'}:
    print("Please insert l, h or c: ")
    command = input("l, h or c: ")
else:
    print("working")

in将检查命令是否在字符串列表中

do
如果命令不在{“l”、“h”、“c”}:
中,它将检查您键入的内容是否在该集合中

如果检查常量组的成员资格,为什么需要或设置?使用元组或列表似乎很好。我不记得文字值集是否相等optimized@jamylak:因为它是最快的选项,在Python 3中优化为作为常量存储的冻结集。@jamylak:see和@jamylak集成员身份在平均情况下是
O(1)
,而不是
O(n)的列表/元组
。如果要检查许多命令,而不是将大量的
子句链接在一起,那么set方法也非常好。更好的方法是:如果命令不在{'l','h','c'}中,则使用
;Python优化了这种情况,您将得到一个O(1)测试。@MartijnPieters一个如何优于另一个?请参阅和@MartijnPietersok@MartijnPieters一个问题:为什么要使用集合?