需要解决 if/else 和 "and" 问题



只是想让python能够判断我制作的a和b的两个函数中是否都有字符串"John",但它不起作用

我尝试使用 elif(例如:"elif "John"不在 a 和 b 中"而不是那里的"else"(,但这并没有区别。我尝试从 b 中删除 Jack 并只留下引号,这实际上返回"其中只有一个叫 John",这当然是正确的,因为当我将其更改为仅引号时,b 没有说"John",但 b 在字符串是"Jack"时也没有说 john,那么当我把"Jack"放在那里时为什么它不说"只有一个叫 John"呢?(对不起,我的标点符号使用不好,我很不擅长(

下面是供您查看的代码:

a = "John"
b = "Jack"
if "John" in a and b:
print("Both are named John")
else:
print("Only one of them are named John")

当 b 没有字符串"John"时,我预计结果会说"只有一个叫约翰",但它总是说"两个都叫约翰">

你用了if "John" in a and b:意思是if ("John" in a) and b:

这是因为in的优先级高于or

您需要这样做:

a = "John"
b = "Jack"
if "John" in a and "John" in b:
print("Both are named John")
else:
print("Only one of them are named John")

注意if "John" in a and "John" in b:相当于if ("John" in a) and ("John" in b):

最新更新