-1

Just trying to get python to be able to tell if two functions I've made a and b both have the string "John" in it, but it's not working

I've tried using elif (example: 'elif "John" not in a and b' instead of the "else" there) but that didn't make a difference. I tried removing Jack from b and only leaving the quotation marks, that actually returns "Only one of them are named John", this is correct of course because when I change it to just the quotation marks, b does not say "John", but b does not say john when the string is "Jack" either, then why does it not say "Only one of them are named John" when I put "Jack" there? (sorry for my bad punctuation use, I'm very bad at it)

Here's the code for you to look at:

    a = "John"
    b = "Jack"

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

I expected the result to say "Only one of them are named John" when b didn't have the string "John", but it always says "Both are named John"

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328

1 Answers1

3

You used if "John" in a and b: which meant if ("John" in a) and b:

This is because in has higher precedence than or.

You need to do this:

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")

Pay attention to if "John" in a and "John" in b: which is equivalent to if ("John" in a) and ("John" in b):

Yash
  • 3,438
  • 2
  • 17
  • 33
  • 1
    omg! now that you actually point it out, I realized how simple it was ugh! I'm so stupid lol. Thank you so much for the help dude, really appreciate it! – Neo Kovacs Aug 26 '19 at 16:50
  • 1
    I upvoted it, but it won't let me accept it until 7 minutes have passed :( – Neo Kovacs Aug 26 '19 at 16:53