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 Conditional Statements Example

age = 15
 
if age >= 18:
  print("You are an adult.")
elif age >= 13:
  print("You are a teenager.")
else:
  print("You are a minor.")

Code Explanation

  • Line 1: We store the number 15 in a variable called age.
  • Line 3: We check if the number in the age variable is 18 or bigger.
  • Line 4: If it is, we say “You are an adult.”
  • Line 5: If not, we check if the number is 13 or bigger.
  • Line 6: If it is, we say “You are a teenager.”
  • Line 7: If it’s not 13 or bigger, we do this last part.
  • Line 8: We say “You are a minor.”

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

Example

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

Code Explanation

  • Line 1: Sets a variable is_raining to True.
  • Line 2: Checks if the value of is_raining is True.
    • Line 3: Prints the message 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.")

Code Explanation

  • Line 1: Sets a variable temperature to 25.
  • Line 2: Checks if the temperature is greater than 30.
    • Line 3: Prints the message 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.


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 code runs if condition is True.
  • (condition): This is where you write the rule to be tested. Returns True or False.
  • action_if_false: This code runs if condition is False.

Example

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

Code Explanation

  • Line 1: Sets the variable hour to a value (change it to see different greetings).
  • Line 2: 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 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

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.")

Code 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: Prints message 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: Prints message if the score is 80 or higher (the first condition was False).
  • Line 8: Prints this message if none of the above conditions are True (score less than 80).

Output

Great job! You got a B.


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

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.")

Code 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 runs if the age is 13 or older, but the movie rating is inappropriate.
  • Line 9: Outer else 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.")

Code Explanation

  • Line 1-2: Sets the variables.
  • Line 4: 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.")

Code Explanation

  • Line 1-2: Sets the variables.
  • Line 4: 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.")

Code Explanation

  • Line 1: Sets the variable.
  • Line 3: 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.