python - if语句中的Python“and”被识别为“or”
问题描述
嗨,我想检查用户输入是否长 3 个字符,第二个是空格,第一个和第三个是 1,2 或 3,所以用户应该输入“1 3”或“2 2”等。
我写了这个
correct_cord = False
cord = ["1", "2", "3"]
while not correct_cord:
self.move = input("Enter cells: ")
if (self.move[1] != " ") and (len(self.move) != 3):
print("You should enter coordinates in form 'X Y'")
else:
if not self.move[0].isnumeric() and not self.move[2].isnumeric():
print("You should enter numbers!")
elif self.move[0] not in cord and self.move[2] not in cord:
print("Coordinates should be from 1 to 3!")
else:
correct_cord = True
self.move = self.move.split()
print(self.move)
问题是:
- 当用户输入“x xx”时,它会打印“你应该输入数字!” 而不是“您应该按预期以'XY'形式输入坐标” - 输入有4个字符而不是3个所以它不应该传递给else语句
- 当用户输入“xxx”时,它会打印“你应该输入数字!” 而不是“您应该按预期以'XY'形式输入坐标” - 输入有3个字符,但第二个不是空格
- 当用户输入“1 x”时,它会打印结果而不是“您应该输入数字!” - 第三个字符不是数字
- 当用户输入“1 4”时,它会打印结果而不是“坐标应该是从 1 到 3!”
它有什么问题?!
解决方案
分解问题:
self.move = input("Enter cells: ") # <-- user enters "x xx"
现在,以下陈述成立:
(self.move == "x xx") == True
(self.move[1] != " ") == False # the second character is a space
(len(self.move) != 3) == True # the length is not 3
因为您已将其与and
操作员配对,所以您最终得到:
(False and True) == False # they aren't both True
if False:
print("You should enter coordinates in form 'X Y'")
else:
...
哪个正确地采用了else
分支-您的逻辑有缺陷。
您可能想要交换and
,or
因为这些测试中的任何一个失败都会 触发警告(不是两个测试都失败)。
(self.move[1] != " ") == False # the second character is a space
(len(self.move) != 3) == True # the length is not 3
if False or True:
print("You should enter coordinates in form 'X Y'")
else:
...
另一种方法可能是进行“肯定”测试,这有助于推理 - 很容易与否定混淆......这里我们确认“我们的所有测试都通过”(在用 反转结果之前not
),而不是测试如果“我们的任何测试失败”。
if not ( (self.move[1] == " ") and (len(self.move) == 3) ):
print("You should enter coordinates in form 'X Y'")
else:
...
作为一般说明,在尝试访问其内容之前测试变量的边界也是明智的。
在下面的示例中,在检查len(x) == 3
之前会失败x[1] == " "
,并且测试会短路,这意味着x[1]
甚至永远不会评估,并且不会引发IndexError
异常。
if not ( (len(self.move) == 3) and (self.move[1] == " ") ):
print("You should enter coordinates in form 'X Y'")
else:
...
在这里,b()
永远不会被调用:
>>> def a():
... print('a')
... return False
...
>>> def b():
... print('b')
... return True
...
>>> if a() and b():
... print('yay')
... else:
... print('boo')
...
a
boo
推荐阅读
- android - 使用 ndk arm-linux-androideabi-clang++ 编译器为 android 构建 grpc C++
- javascript - 空调功能
- css - 在引导程序 4 中关闭折叠的导航栏后,导航栏项目仍然可见一段时间
- python - 无法写入 TensorArray 索引,因为值形状与 TensorArray 的推断元素形状不兼容
- javascript - console.log 返回 [object Object]
- php - 卡在通知系统上
- node.js - 无法在 Express.js 中获取处理 request.params 的服务器结果
- android - Android中的上下文是复杂策略设计模式的实现吗?
- python - 循环中的numpy column_stack
- swift - 如何使用 UITabBarController 实现此布局