Solved

if color == "red" or "blue" is always True

CharlieHOP edited

Took me ages: if color == "red" or "blue": runs even when color is "green".

10

Comments 5

Log in to join the discussion.

Log in Create account
  1. LucasVD Solutionreplies: 1

    Python reads it as (color == "red") or ("blue"). A non-empty string is truthy, so the whole thing is always True.

    Write either:

    if color == "red" or color == "blue":
    if color in ("red", "blue"):

    The second is the Pythonic way.

    5
    1. CharlieHOP

      The in version is so much nicer.

      0
    2. EmmaCodes

      One of the most common beginner bugs in every language that allows truthy strings. You're in good company.

      1
      1. LiamBytereplies: 1

        or also returns one of its values, not just True/False: name = user_input or "Anonymous" is a neat default.

        2
        1. OllieGrant

          Careful with that default trick when 0 is a valid input though.

          2