Python’s if statements are the decision-makers of your code. They allow your program to look at a situation and decide which path to take based on whether a condition is true or false.
If Statement
The if statement is the most basic way to control the flow of your program. It tells the computer, “Only perform this specific action if this condition is true.” If the condition is false, the computer simply skips that block of code entirely and moves on to the next part.
age=20 ifage>=18: print("Welcome to the adult section!")
Elif Statement
Short for “else if,” the elif statement allows you to check for multiple specific conditions in a row after the first if. It is perfect for situations where there are more than two possible outcomes, like grading a quiz where scores fall into A, B, C buckets.
score=85 ifscore>=90: print("Grade: A") #output Grade A for scores 90 and above elifscore>=80: print("Grade: B") #output Grade B for scores 80 and above
Else Statement
Think of the else statement as your “safety net” or backup plan. It doesn’t have a condition of its own because it automatically catches anything that didn’t meet the requirements of the if or elif statements above it.
If you only have one single line of code to run after your condition, you can put it all on one line to keep your code clean and compact. This is often used for very simple checks where a full block of code would feel like overkill for the reader.
A nested if is simply an if statement placed inside another if statement. This is useful when you need to pass a second “test” only after passing the first one, like checking if a person is logged in and then checking if they have admin permissions.
The ternary operator is Python’s fancy name for the shorthand if-else expression—think of it as a three-part shortcut: condition-based choice in one go. It’s especially handy in functions or loops for on-the-fly decisions, like setting colors based on status. Pros love it for brevity, but beginners should practice to get the “true if condition else false” flow right.