If Statements in Python

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
if age >= 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
if score >= 90:
  print("Grade: A") #output Grade A for scores 90 and above
elif score >= 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.
temperature = 15
if temperature > 25:
  print("It's warm outside!")
else:
  print("Bundle up—it's chilly.")

Shorthand If (Inline If Expression)

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.

speed = 60
message = "Fast!" if speed > 50 else "Slowpoke"
print(message)  # Outputs: Fast!

Nested If

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.
is_logged_in = True
is_admin = True
if is_logged_in:
  if is_admin:
      print("Access full dashboard")
  else:
      print("Limited access")
else:
  print("Please log in")

Ternary Operator (Conditional Expression)

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.
value = 7
result = "Even" if value % 2 == 0 else "Odd"
print(result)  # Outputs: Odd
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top