在 if __ is __ 语句中使用 .lower 或 'or' 会导致 python 中的 if 语句流不正确 3.6

Using .lower or 'or' in if __ is __ statement causes incorrect if statement flow in python 3.6

我进行了搜索,但似乎找不到遇到过同样问题的人,尽管我对 python 还很陌生,而且很可能只是用户错误。

我在 if 语句中同时使用 'or' 和 .lower 时遇到问题。如果我使用代码:

print('press Y to continue or Q to quit')
end = input()
if end is 'y':
    continue
else:
    break

然后我的代码可以正常工作,尽管如果用户输入大写 Y,程序会继续执行 else 语句并结束程序。如果我使用以下代码:

print('press Y to continue or Q to quit')
end = input()
end = end.lower()
if end is 'y': #I have also tried end.lower() here, removing the line above
    continue
else:
    break

程序继续中断任何输入。如果我在 if 语句之前打印 'end',它会 returns:

<built-in method lower of str object at 0x7fa6b8176f80>

我也试过将 is 替换为 ==,结果相同。我对 if is 语句的措辞有问题吗?

你有两个问题:

  1. 您使用的是 end.lower 而不是 end.lower()。这意味着 Python 将看到方法 str.lower 而不是其结果。
  2. 您使用 is 而不是 ==。这会强制 Python 检查两者是否是同一个对象,即在您计算机上的相同物理 space 中。 == 检查它们是否具有相同的值。一般来说,你几乎总是想要 ==.