if conditional statements in Python; what’s the catch?

Ikponmwosa Esther
2 min readMay 1, 2020

Decision making is required whenever we want to execute a particular line of code only if a particular condition is meant. The if…., elif…. and else…; statements are used in python for decision making.

In this article you will learn how to use the if, elif and else statement for decision making in python.

If, elif and else statement is a built-in function to check through a list of items in python.

if condition:

It is used when you need to print out the result when one of the conditions is true or false.

Syntax:

if [boolean expression]:    [statement1]    [statement2]    [statementN]

Boolean expression is a logical statement that is either True or false. Boolean expressions can compare data of any type as long as both parts of the expression have the same data type.

Here python will only execute the Boolean expression, only if the expression is true. Use the : symbol and press Enter after the expression to start a block with increased indent. All statement made under this indentation will be evaluated if the Boolean statement is true.

if 2 < 5:
print(“2 is less than 5”)

In the example above if 2<5 evaluates true, it will execute the code. the if block starts from new line after :. All the statements under the if condition start with an increased indentation. Above, if block contains only one statement.

Output:

2 is less than 5

else condition:

It is used to evaluate an alternate block of statement if the Boolean expression in the if condition is not true.

Syntax:

if [boolean expression]:    [statement1]    [statement2]    [statementN]else:    [statement1]    [statement2]    [statementN]

The “else” condition is usually used when you have to judge one statement on the basis of other. If one condition goes wrong, then there should be another condition that should justify the statement or logic.

Example

if 2 > 5:    print (“2 is greater than 5”)else:    print (“2 is less than 5”)

Output:

2 is less than 5

elif condition:

The elif condition is used to include multiple conditional expressions between if and else.

Syntax:

if [Boolean expression]:    [statements]elif [Boolean expression]:    [statements]elif [Boolean expression]:    [statements]elif [Boolean expression]:    [statements]else:    [statements]

By using “elif” condition, you are telling the program to print out the third condition or possibility when the other condition goes wrong or incorrect.

Example

x=5
if x==0:
print('x is 0')
elif x==3:
print('x is 3')
elif x==5:
print('x is 5')
else:
print('x is something else')

Output:

x is 5

I hope this help us with the basic knowledge of if conditional statement.

--

--