Conditional Statements


Control Flow: Conditional Statements

Learn how to control the flow of your Python programs using conditional logic.


1. if Statement

The if statement executes a block of code if a condition is true.

x = 10 if x > 5:     print("x is greater than 5")
Output:
x is greater than 5



2. if-else Statement

Use else to execute code when the if condition is false.

age = 16 if age >= 18:     print("You can vote.") else:     print("You are too young to vote.")
Output:
You are too young to vote.



3. if-elif-else Chain

Use elif to check multiple conditions.

score = 85 if score >= 90:     print("Grade A") elif score >= 80:     print("Grade B") else:     print("Grade C")
Output:
Grade B



4. Comparison Operators

These are used to compare values.

  • == Equal to
  • != Not equal to
  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to



5. Logical Operators

Combine multiple conditions using logical operators:

x = 10 if x > 5 and x < 20:     print("x is between 5 and 20")
Output:
x is between 5 and 20



6. not Operator

logged_in = False if not logged_in:     print("Please log in.")
Output:
Please log in.



7. Nested Conditionals

Conditionals inside other conditionals are called nested conditionals.

x = 10 if x > 0:     if x % 2 == 0:         print("Positive even number")     else:         print("Positive odd number")
Output:
Positive even number