Conditional Statements

Understand Python conditional statements like if, elif, and else with syntax, examples, and key tips. Learn how to control the flow of your Python programs.

Loading...
Conditional Statements

In Python, conditional statements are used to make decisions in the code based on certain conditions. They allow us to execute different blocks of code depending on whether a specific condition evaluates to True or False.

Types of Conditional Statements in Python

Python has following conditional statements:

if-else statement

If the condition in the if statement evaluates to true, the code inside the if block will be executed; otherwise, the code within the else block will be executed.

Syntax:

if condition:
  # Code to execute if condition is True
else:
  # Code to execute if condition is False

Example:

num = int(input("Enter a number: "))
if num < 0:
  print("Number is negative.")
else:
  print("Number is positive.")

elif statement

The elif statement (short for "else if") is used when there are multiple conditions to evaluate. It is placed between if and else.

Syntax:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if all above conditions are False

Example:

num = int(input("Enter a number: "))
if num < 0:
    print("Number is negative.")
elif num == 0:
    print("Number is zero.")
else:
    print("Number is positive.")

Nested if statements

if statements can be nested within other if, elif, or else blocks to evaluate additional conditions.

Syntax:

if condition1:
    # Code to execute if condition1 is True
    if condition2:
        # Code to execute if condition2 is True
    elif condition3:
        # Code to execute if condition3 is True
    else:
        # Code to execute if all inner conditions are False
else:
    # Code to execute if condition1 is False

Example:

num = int(input("Enter a number: "))
if num < 0:
    print("Number is negative.")
elif num > 0:
    if num <= 50:
        print("Number is between 1 and 50.")
    elif num > 50 and num <= 70:
        print("Number is between 51 and 70.")
    else:
        print("Number is greater than 70.")
else:
    print("Number is zero.")

Key Points About Conditional Statements

  1. Indentation Matters:
    • Python uses indentation (spaces or tabs) to show which code belongs to a condition.
    • Make sure all lines in a block have the same indentation.
  2. Only One else:
    • You can use many if and elif statements, but only one else is allowed.
  3. Comparison and Logical Operators:
    • Conditions use operators like:
      • == (equal), != (not equal), < (less than), > (greater than).
      • and, or, not to combine conditions.
  4. Order of Checks:
    • Python checks conditions one by one. If a condition is true, the following conditions are skipped.

Support my work!