Logical Operators: and
Sometimes one condition isn't enough. “If it's Friday and it's warmer than 20 °C, I'll go out” is made of two conditions joined by the word “and”. Python uses that very word, and:
day = "Friday"
temperature = 25
if day == "Friday" and temperature > 20:
print("I'm going out")This prints:
I'm going outand is a logical operator: it joins two conditions into one. The joined condition is true only if both parts are true. If even one of them is false, the whole condition is false:
True and TrueisTrueTrue and FalseisFalseFalse and TrueisFalseFalse and FalseisFalse
You can join more conditions in a row: a and b and c is true only if all three are true.
Each part must be a complete comparison. “Age from 13 to 19” is age >= 13 and age <= 19. If you shorten it the way we speak, to age >= 13 and <= 19, the program ends with SyntaxError: invalid syntax: Python doesn't know what <= 19 should compare.
Instructions
- 1
Write an
ifstatement that printsWelcomeonly ifusernameis"admin"and at the same timepasswordis"kitten42". Join the two comparisons withand. - 2
Add an
elsebranch that printsWrong username or password. Then try a wrong password: changepasswordto"kitten". One false part is enough to make the whole condition false, so the program printsWrong username or password.