menu

DEEP DIVE INTO

Python

Topic:control flow (if, else, elif)

menu

Control flow in Python is a fundamental concept that governs the order in which statements are executed within a program. It allows you to make decisions, repeat actions, and handle exceptions.

Let's dive deeper into the various aspects of control flow in Python:

1. Sequential Execution:

By default, Python executes statements sequentially, one after the other, from top to bottom in a script or program.

Syntax:

pythonstatement1
statement2
statement3
# Statements are executed in this order

Example:

print('Hello World')
print('I love ❤️ programming')
print('Python is awesome 👍')

2. Conditional Statements:

Conditional statements, primarily implemented using if, elif, and else, allow you to execute different blocks of code based on specified conditions.

Syntax:

pythonif condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition1 is False and condition2 is True
else:
    # Code to execute if both condition1 and condition2 are False

Example:

pythonx = 10

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

In this example, the code uses if, elif, and else to make decisions based on the value of the variable x.

You will notice there are no curly braces ({}) in if, elif, or else sections, which you will find generally in other languages.

1280 x 720 px