Lesson 15/48 ยท ๐Ÿ”€ Making Decisions
๐Ÿ”€ Making DecisionsLesson 15/48
Phase 2 ยท Making Decisions15 min

Comparison Operators

Ask yes/no questions, the foundation of all decisions in code

Before your program can make decisions, it needs to be able to ask questions.
Is this number greater than 10? Is this password correct? Has the user logged in? All of these are yes/no questions, and Python answers them with True or False.
The tools for asking these questions are comparison operators.
The 6 comparison operators:
  • == equals: 5 == 5 โ†’ True
  • != not equals: 5 != 3 โ†’ True
  • < less than: 3 < 10 โ†’ True
  • > greater than: 10 > 3 โ†’ True
  • <= less than or equal: 5 <= 5 โ†’ True
  • >= greater than or equal: 6 >= 7 โ†’ False
  • Comparisons in actionpython
    print(10 == 10)   # True
    print(10 == 10.0) # True  (int and float compare fine)
    print(5 != 3)     # True
    print(3 < 5)      # True
    print(5 <= 5)     # True
    print("hi" == "hi")  # True (strings too)
    print("hi" == "Hi")  # False (case sensitive!)
    The most common beginner mistake in all of programming:
    = assigns a value to a variable: x = 5 means "store 5 in x"== checks if two things are equal: x == 5 means "is x equal to 5?"
    ```pythonage = 18 # Assigns 18 to ageage == 18 # Asks "is age equal to 18?" (evaluates to True)`
    Using = where you meant == causes either a SyntaxError or a very confusing bug.
    ๐Ÿค”Quick Check

    What does print(10 == 10.0) output?

    ๐Ÿค”Quick Check

    What is the difference between = and == in Python?

    Practice Exercises

    0/3 solved
    Exercise 1 of 3easy
    โฑ 00:00

    True or False?

    Print the result of these comparisons (each on its own line):- Is 15 greater than 10?- Is "python" equal to "Python"?- Is 7 not equal to 7?- Is 100 greater than or equal to 100?
    Expected output:TrueFalseFalseTrue
    solution.py
    1 / 3
    Exercise 2 of 3easyFix the Bug
    โฑ 00:00

    Fix the Assignment Bug

    The code below has a common bug: it uses = when it should use ==.Fix it so it prints the result of comparing x to 10.Expected output: False
    solution.py
    2 / 3
    Exercise 3 of 3easy
    โฑ 00:00

    Password Checker

    Check if the entered password matches the stored password.stored = "secret123"entered = "Secret123"Print the result of checking if they match.Expected output: False
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion