Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 out

and 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 True is True
  • True and False is False
  • False and True is False
  • False and False is False

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. 1

    Write an if statement that prints Welcome only if username is "admin" and at the same time password is "kitten42". Join the two comparisons with and.

  2. 2

    Add an else branch that prints Wrong username or password. Then try a wrong password: change password to "kitten". One false part is enough to make the whole condition false, so the program prints Wrong username or password.

Back

10/15

  1. 1. The if Statement
  2. 2. Blocks of Code
  3. 3. The else Branch
  4. 4. Quiz: if and else
  5. 5. Comparison Operators
  6. 6. Quiz: Arranging a Condition
  7. 7. Boolean Values
  8. 8. More Options: elif
  9. 9. Quiz: elif
  10. 10. Logical Operators: and
  11. 11. Quiz: and
  12. 12. Logical Operators: or
  13. 13. Logical Operators: not
  14. 14. Nested Conditions
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.