只是想讓python能夠判斷我制作的兩個函數a和b是否都有字符串“John”,但它不起作用我嘗試過使用 elif(例如:'elif "John" not in a and b' 而不是那里的 "else"),但這并沒有什么不同。我嘗試從 b 中刪除 Jack,只留下引號,實際上返回“只有一個叫 John”,這當然是正確的,因為當我將其更改為引號時,b 不會說“John”,但是當字符串是“Jack”時,b 也沒有說 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”時,我希望結果會說“只有一個叫 John”,但它總是說“Both are named John”
1 回答

繁星點點滴滴
TA貢獻1803條經驗 獲得超3個贊
你用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):
添加回答
舉報
0/150
提交
取消