Python Control Statement: if

Python if Statement

The if statement in Python is a control statement that allows you to execute code based on a condition. When the condition is true, the specified block of code runs, and when false, another block runs, or no operation is performed. In Python, the if statement is structured as follows:

Basic Structure:

if condition:
    code to execute
    

Example:

age = 18

if age >= 18:
    print("You are an adult.")
    

In the above code, since age is 18, the condition age >= 18 evaluates to true, and print("You are an adult.") is executed. If the condition is false, this block will be ignored.

Using else

else lets you specify code to run when the condition is false.

age = 16

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

Here, since age is 16, the condition is false, and the else block runs.

Using elif

Sometimes you need to check multiple conditions. You can use elif to check additional conditions.

age = 17

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

In this code, since age is 17, the first condition is false, but the second elif condition is true, so “You are a teenager.” is printed.

Nested if Statements

You can also use an if statement within another if statement. This is called a nested if statement.

age = 20
is_student = True

if age >= 18:
    if is_student:
        print("You are an adult and a student.")
    else:
        print("You are an adult but not a student.")
    

Here, since the condition age >= 18 is true, it enters the first if block, and since the if is_student: condition is also true, “You are an adult and a student.” is printed.

Comparison Operators and Logical Operators

In the if statement, you can use various comparison and logical operators.

Comparison Operators:

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

Logical Operators:

  • and: True if both conditions are true
  • or: True if at least one condition is true
  • not: The opposite of the condition

Example:

age = 22
is_student = False

if age >= 18 and not is_student:
    print("You are an adult and not a student.")
    

In this code, the condition age >= 18 is true, and not is_student is also true, so the final if condition is satisfied, and “You are an adult and not a student.” is printed.

Thus, the if statement allows handling various conditions in a program. By appropriately utilizing it, you can implement complex logic.