Python if Statement

Learn how Python if statement controls code execution based on conditions. Master conditional logic and create programs that make intelligent decisions.

Python-if-Statement
Table of Contents

Python Conditional Statements

Python’s conditional statements (like if, if-else, and if-elif-else) allow you to control the flow of your program by executing different code blocks based on whether specific conditions are True or False.

Python if Statement

The most basic form. Here’s the pattern:

Syntax

if (condition):
    # Code to run if the condition is True

Use case: Executing code only if a specific condition holds. 

Example: Checking if a user’s age is above 18 to allow access.

Python if-else Statement

Adds another path. The structure:

Syntax

if (condition):
    # Code to run if the condition is True
else:
    # Code to run if the condition is False

Use case: Two distinct actions based on the condition. 

Example: Displaying “Welcome” if a user is logged in, “Please log in” otherwise.

Python if-elif-else Statement (The Elif Ladder)

Handles multiple possibilities. The flow:

Syntax

if (condition1):  
    # Code to run if condition1 is True
elif (condition2):
    # Code to run if condition1 is False BUT condition2 is True
elif (condition3):
    # ... (You can have many 'elif' blocks)
else:
    # Code to run if none of the above conditions are True

Use case: Multiple branching paths. 

Example: Assigning a letter grade (A, B, C…) based on a numerical score.


Python if statement

Python if statement lets your program decide based on a true or false condition. Here’s a quick look:

Syntax

if (condition):
  # do something if condition is True
  • Line 1: This keyword starts the check.
    • (condition): This is where you write the rule to be tested.
    • Line 2: These lines with “#” are where you write the code to run if the condition is True.

Example

is_raining = True
if is_raining:  # Check if it's raining
  print("Take an umbrella!")

Explanation

  • Line 1: This line sets a variable is_raining to True.
  • Line 2: This checks if the value of is_raining is True.
    • Line 3: This message is printed if it’s raining (True).

Output

Take an umbrella!


Python if…else Statement

The Python if…else statement lets your program choose between two actions based on a condition. Here’s the basic structure:

Syntax

if (condition):
  # do something if condition is True
else:
  # do something else if condition is False

The else part is optional and runs code if the condition is False.

Example

temperature = 25
if temperature > 30:
  print("It's a hot day!")
else:
  print("The weather is pleasant.")

Explanation

  • Line 1: Sets a variable temperature to 25.
  • Line 2: Checks if the temperature is greater than 30.
    • Line 3: This line prints if the temperature is above 30.
  • Line 4: Since the temperature is not above 30, the else block runs.
    • Line 5: This line prints because the condition in the if block was False.

Output

The weather is pleasant.


Python if…else Statement in One Line (ShortHand if Statement)

Python if…else statement can be condensed into one line for simple decisions. Here’s how:

Syntax

action_if_true if (condition) else action_if_false
  • action_if_true: This is the code to run if the condition is True.
  • (condition): This is where you write the rule to be tested.
  • action_if_false: This is the code to run if the condition is False.

Example

hour = 14  # Change this value to see different outputs
greeting = "Good morning!" if hour < 12 else "Good afternoon!"
print(greeting)

Explanation

  • Line 1: Sets the variable hour to a value (change it to see different greetings).
  • Line 2: This line checks if hour is less than 12. If True, “Good morning!” is assigned to greeting. If False (hour is 14), “Good afternoon!” is assigned.
  • Line 3: Prints the greeting based on the time of day (as defined by the value in hour).

Output

Good afternoon!


Python if…elif…else Statement (elif Ladder)

Python if…elif…else statement, also called an “elif ladder,” lets your program check multiple conditions and run specific code for each. Imagine a ladder of checks!

Syntax

if (condition1):
  # do something if condition1 is True
elif (condition2):
  # do something else if condition1 is False and condition2 is True
else:
  # do something if none of the above are True
  • Line 1 This sequence allows for multiple condition checks.
    • (condition1): The first rule to be tested. If True, the code below it runs.
  • Line 3: This optional part checks another condition if condition1 is False.
  • Line 5: This part (also optional) runs code if none of the conditions above are True.

For example, giving a grade based on a score:

Example

score = 85

if score >= 90:
  print("Excellent! You got an A.")
elif score >= 80:
  print("Great job! You got a B.")
else:
  print("Keep practicing! You got a C.")

Explanation

  • Line 1: Sets the variable score to 85 (change it to see different outputs).
  • Line 3: Checks if the score is 90 or higher.
    • Line 4: This message is printed if the score is 90 or higher.
  • Line 5: If the first condition is False, this checks if the score is 80 or higher.
    • Line 6: This message is printed if the score is 80 or higher (the first condition was False).
  • Line 8: This message is printed if none of the above conditions are True (score less than 80).

Output

Great job! You got a B.


Python elif Statement in One Line (ShortHand if…elif…else Statement)

Python’s elif statement can be used in one line for simple conditional checks within an if…else structure. Here’s how:

Syntax

action_if_true1 if (condition1) else action_if_true2 if (condition2) else action_if_false
  • action_if_true1: This is the code to run if condition1 is True.
    • (condition1): The first rule to be tested.
  • action_if_true2: This is the code to run if condition1 is False and condition2 is True.
    • (condition2): The second rule to be tested (only if the first fails).
  • action_if_false: This is the code to run if condition1 and condition2 are False.

For a quick check, like choosing a drink based on age:

Example

age = 20

drink = "Milk" if age < 18 else "Coffee" if age >= 18 and age < 21 else "Tea"
print(drink)

Explanation

  • Line 1: Sets the variable age to 20 (change it to see different outputs).
  • Line 3: This line checks the age. If under 18, “Milk” is assigned to drink. If 18 to 20 (and the first condition is False), “Coffee” is assigned. If none of the above are True (over 21), “Tea” is assigned.
  • Line 4: Prints the chosen drink based on age.

Output

Coffee


Nested if Statements

Nested if statements allow you to create more complex decision-making in your Python programs. Imagine stacking if statements inside each other!

Syntax

if (condition1):
  # do something if condition1 is True
  if (condition2):  # Nested if within the first if block
    # do something if BOTH condition1 and condition2 are True
  else:
    # do something else if condition1 is True, but condition2 is False
else:
  # do something if condition1 is False
  • Line 1: The first main condition to be tested.
    • Line 2: Code runs here if condition1 is True.
    • Line 3: An optional nested if to check another condition within the first if block.
      • Line 4: Code runs here only if both condition1 and condition2 are True.
    • Line 5: This nested else runs code if condition1 is True, but condition2 is False.
  • Line 7: This outer else runs code if the first condition1 is False.

For example, checking eligibility for a movie based on age and rating:

Example

age = 15
movie_rating = "PG-13"

if age >= 13:
  if movie_rating == "PG-13" or movie_rating == "G":
    print("You can watch this movie!")
  else:
    print("This movie is rated", movie_rating, ". You may need parental guidance.")
else:
  print("Sorry, you must be at least 13 to watch this movie.")

Explanation

  • Line 1-2: Set the variables.
  • Line 4: Checks if the age is 13 or older.
    • Line 5: Nested check within the first if to see if the movie rating is allowed for the age group.
      • Line 6: Prints this if both age and rating allow it.
    • Line 7: Nested else that runs if the age is 13 or older but the movie rating is inappropriate.
  • Line 9: Outer else that runs if younger than 13.

Output

You can watch this movie!


Short Circuit Evaluation (and, or, not Operators)

Python’s logical operators, and, or, and not, help you combine conditions in your if statements. Imagine these as tools for making complex decisions!

And Operator

The and operator in Python acts like a strict bouncer for your code’s decisions in if statements. It checks multiple conditions, and only if all of them are True, will the code after the if statement run. Imagine an and like a key with multiple teeth – all teeth must fit perfectly to unlock!

Syntax

condition1 and condition2
  • condition1: The first rule to be checked.
  • condition2: The second rule to be checked (and so on).

For example, checking if someone is old enough to drive and has a license:

Example

age = 18
has_license = True

if age >= 16 and has_license:  # Both conditions with "and"
  print("You can drive!")
else:
  print("Sorry, you cannot drive yet.")

Explanation

  • Line 1-2: Sets the variables.
  • Line 4: This checks if both age is 16 or over and has_license is True. Since both conditions are True, the code after the if runs.
    • Line 5: This line is printed because both requirements are met.
  • Line 7: This block wouldn’t run because the and condition was True.

Output

You can drive!

Or Operator

The or operator in Python is more lenient than and in if statements. It checks multiple conditions, and if at least one of them is True, the code after the if statement runs. Imagine an or like a loose gate – only one side needs to be open for passage!

Syntax

condition1 or condition2
  • condition1: The first rule to be checked.
  • condition2: The second rule to be checked (and so on).

For example, checking if someone is a student or a teacher for a discount:

Example

is_student = False
is_teacher = True

if is_student or is_teacher:  # Either condition with "or"
  print("You qualify for the discount!")
else:
  print("Sorry, this discount is for students and teachers only.")

Explanation

  • Line 1-2: Sets the variables.
  • Line 4: This checks if is_student is True oris_teacher is True. Since is_teacher is True, the condition is True overall due to the or operator.
    • Line 5: This line is printed because at least one condition was met.
  • Line 7: This block wouldn’t run because the or condition was True.

Output

You qualify for the discount!

Not Operator

The not operator in Python flips the outcome of a condition in if statements. It acts like a switch – if a condition is True, it becomes False, and vice versa. Imagine not as a toggle button!

Syntax

not (condition)

(condition): The rule to be checked. The not operator flips the outcome of this condition.

For example, checking if someone is not an adult (meaning a child):

Example

age = 12

if not (age >= 18):  # "not" inverts the condition
  print("You are considered a child.")
else:
  print("You are an adult.")

Explanation

  • Line 1: Sets the variable.
  • Line 3: This checks the opposite of age >= 18. Since 12 is not greater than or equal to 18, the condition (after the not) is True.
    • Line 4: This line is printed because the condition (which checks for not being an adult) was True.
  • Line 6: This block wouldn’t run because the condition was True due to the not operator.

Output

You are considered a child.