【发布时间】:2023-02-01 16:56:02
【问题描述】:
我尝试使用输入“AC039”运行此代码
code = input("Enter code: ").upper()
if code[0] != ('N' or 'A' or 'C' ):
print("The first character must be N, A or C")
else:
print("Pass!")
它给了我输出错误结果:
The first character must be N, A or C
但是,如果我使用“not in”将“AC039”输入到下面的代码中,
code = input("Enter code: ").upper()
if code[0] not in ["N", "A", "C"]:
print("The first character must be N, A or C")
else:
print("Pass!")
结果输出是:
print("Pass!")
为什么“!=”不适用于第一组代码,因为 code[0] 和 'A' 都是字符串类型?
我在 code[0] 上使用 type 函数运行了一个检查,它返回了字符串类型。
code = input("Enter code: ").upper()
print(type(code[0]))
print(type('A'))
回报:
<class 'str'>
<class 'str'>
【问题讨论】:
-
code[0]和'A'可能是同一类型,但这并不意味着您正在应用的操作是正确的操作。 -
如果变量 = ('N' 或 'A' 或 'C' ),则变量 == "N"。这是“或”运算符的属性。请记住,先执行括号中的某些代码。
-
@Kerighan 为什么 ('N' 或 'A' 或 'C') 只接受“N”?你能给我建议吗,因为我想我在某处误解了一个概念
-
使用
if code[0] not in ['N', 'A', 'C' ]: -
您期望
('N' or 'A' or 'C')评估什么?