Conditional Structures in Python

python if else conditional statements
10 November 2024

In programming, various conditional statements are used to execute different actions in different situations. In the Python programming language, the most important conditional structure we use is the if statement. This statement allows you to evaluate a specific condition, and if that condition is true, execute a block of code.

Furthermore, in Python, the elif and else statements are used to execute code if the previous conditions were not met. The elif abbreviation stands for "else if" and provides the ability to evaluate other conditions. Finally, with else, we can execute code that is unrelated to any of the previous conditions.

Using conditional structures is very helpful because it can assist you in crafting smart and dynamic programs. For instance, suppose you want to write programs that evaluate whether a number is positive, negative, or zero. By using conditional structures, this task becomes very simple.

In the code below, the way to use if...elif...else in Python to evaluate the state of a given number is demonstrated:


number = 5

if number > 0:
    print("The number is positive")
elif number == 0:
    print("The number is zero")
else:
    print("The number is negative")

Let’s review the above code line by line:

number = 5
Here, a variable named number is defined with the value of 5.

if number > 0:
This line indicates that if the value of number is greater than zero, the block of code specified in the following indent will be executed.

print("The number is positive")
This statement will print "The number is positive" if the previous condition is true.

elif number == 0:
This condition checks if the variable equals zero. If the condition is true, the elif block will execute.

print("The number is zero")
If the second condition is true, the output will be "The number is zero".

else:
If none of the previous conditions are true, the section beneath the else will execute.

print("The number is negative")
This statement, in the situation where all previous conditions are false, will print "The number is negative".

FAQ

?

How can I use the if statement in Python?

?

What is the difference between elif and else in Python?

?

Can I have multiple elif statements?