Comparisons: Auditing the Ledger
Programming isn't just about math; it's about making decisions. To make a decision, the computer needs to compare two values. The result of any comparison is always a Boolean (True or False).
The Comparison Operators
In Python, we use these symbols to "audit" our data:
==Equal to: Checks if two values are the same. (Note: Double==is for comparing; single=is for assigning!)!=Not equal to: Checks if two values are different.>Greater than /<Less than>=Greater than or equal to /<=Less than or equal to
Comparing Strings
You can also compare text! Python checks strings character by character. Note that capitalization matters: "Python" is not the same as "python".
Logic Gates: and, or, and not
Sometimes a single comparison isn't enough. You might need to check if a user has enough money AND if the store is open.
and: ReturnsTrueonly if both sides are True.or: ReturnsTrueif at least one side is True.not: Flips the result (TruebecomesFalse).
[Image of a logic gate truth table for AND, OR, and NOT operations]
🏆 The Ledger Challenge: The Overdraft Check
You are writing a script to see if a transaction should be approved.
Task:
- Create a variable
account_balanceand set it to500. - Create a variable
withdrawal_amountand set it to600. - Create a variable
is_overdraft_protectedand set it toTrue. - Create a variable
can_withdraw. This should beTrueif:- The
account_balanceis greater than or equal to thewithdrawal_amount. - OR if
is_overdraft_protectedisTrue.
- The
- Print
can_withdraw.
Write your code below:
📚 Deep Dive
Next Steps
Now that we can compare values, we can finally tell Python to act on those results using If Statements.