Control Flow Statements in Python { if ,Else, Elif }

Tech Orcus
By -
4 minute read
0

Chapter 5: Control Flow Statements in Python


If-Else-Elif statement in Python

In Python, control flow statements allow you to make decisions based on conditions. This is crucial for creating dynamic programs that react differently depending on user input or data values. The main control flow statements in Python are if, else, and elif.

What are Control Flow Statements?

Control flow statements let your program decide what to do next. For example, you can write code that behaves one way if a condition is true and another way if it’s false. The basic syntax for control flow in Python is:

if condition:
    # code to execute if the condition is true
elif another_condition:
    # code to execute if the second condition is true
else:
    # code to execute if no conditions are true
    

Understanding the if Statement

The if statement checks a condition. If the condition is true, it runs the code indented below it. For example:

x = 10
if x > 5:
    print("x is greater than 5")  # This line runs because x > 5
    

Output: x is greater than 5

Adding Alternatives with else

Use else to run code if the if condition is false. For example:

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")  # This line runs because x <= 5
    

Output: x is not greater than 5

Handling Multiple Conditions with elif

The elif statement (short for "else if") lets you check multiple conditions. Python evaluates conditions from top to bottom, stopping when one is true. Example:

x = 20
if x < 10:
    print("x is less than 10")
elif x == 20:
    print("x is equal to 20")  # This line runs because x == 20
else:
    print("x is greater than 20")
    

Output: x is equal to 20

Important Points

  • Indentation is crucial in Python. The code block under if, elif, or else must be indented.
  • Conditions use comparison operators (e.g., ==, >, <, >=, <=, !=).
  • You can nest if statements inside other if statements for more complex logic.

Example: Nested if Statements

x = 15
if x > 10:
    if x % 2 == 0:
        print("x is even and greater than 10")
    else:
        print("x is odd and greater than 10")
    

Output: x is odd and greater than 10

Practice Questions

  1. Write a program to check if a number is positive, negative, or zero.
  2. Write a program to find the largest of three numbers using if-elif-else.
  3. Write a program to check if a year is a leap year.

Congratulations! You’ve learned how to use if, else, and elif to control the flow of your Python programs. Practice these examples to solidify your understanding.

Post a Comment

0Comments

Post a Comment (0)
Today | 15, April 2025