If Statements: The Fork in the Road
In a real-world ledger, you don't treat every entry the same way. If an account is overdrawn, you flag it. If a payment is massive, you verify it. In Python, we use Conditional Statements (if, elif, and else) to control the flow of our program.
The Basic if Statementβ
The structure of an if statement is simple but strict. You provide a condition, followed by a colon (:). The code that follows must be indented (usually 4 spaces).
Adding an elseβ
What happens if the condition is False? We use the else block to provide a backup plan.
The elif (Else If)β
Sometimes you have more than two options. For example, a ledger might have "Positive," "Zero," and "Negative" states. We use elif to check multiple specific conditions in order.
β οΈ The Golden Rule: Indentationβ
In Python, indentation isn't just for looksβit's part of the grammar. Everything indented under the if statement "belongs" to that decision. If you forget to indent, Python will throw an IndentationError.
π The Ledger Challenge: The Security Gateβ
You are writing a login check for The Python Ledger database.
Task:
- Create a variable
usernameand set it to a string. - Create a variable
is_adminand set it to a Boolean. - Write an
if/elif/elsestructure:- IF the
usernameis "Admin" ANDis_adminisTrue, print: "Full Access Granted." - ELIF the
usernameis "Admin" butis_adminisFalse, print: "Admin access denied. Check permissions." - ELSE, print: "Standard User Access Granted."
- IF the
Write your code below:
π Deep Diveβ
Next Stepsβ
Congratulations! You've mastered the basics of logic. You are now ready for your first Project. We will be building a text-based adventure right inside our browser terminal.