If-Else statement in Python

Last updated Aug 10, 2021

If Statement

If statements are a type of control flow statements that are used to run a particular code or particular set of statements only when a certain condition is satisfied. This is the most simple decision-making statement. For printing a specific message or a specific statement, then this point needs to be ensured that if the condition which is given is true then in that case we use the If statement. If there are multiple conditions in a program then the best suggestion is to use nested If statements.

Let's understand more about the If statement with the help of an example:-

num = 10
if num<20:
    print("num is less than 20")
num is less than 20   

As I had explained about the If Statement that when any statement is true it will give us the output and this is the best example for If Statement in python.

If-Else Statement

The main purpose of the if-else statement is to execute both the true part and the false part of a given condition in a python program. If the condition is true then the if block code is executed and if the given condition is false then the else block code will be executed.

Given below is the example of If-Else Statement:-

a = 20
b = 30
if b>a:
    print("b is greater than a")
else:
    print("b is smaller than a")
b is greater than a   

From the above code, you can clearly see that one statement is correct and the other one is an incorrect statement and the function of the If-Else statement is to print the statement which are needed or which are true when the condition is satisfied.

Elif Statement

The Elif Statement is generally used as If-Elif-Else Statement. Elif stands for Else-If. The If-Elif-Else statement will contain multiple conditional expressions but only one boolean expression evaluates to true and execute the respective block of statements. The most important fact about the If-Elif-Else statement is that you can only use the If and Else statement only once whereas you can use Elif Statement multiple times in your python program.

So let's understand this If-Elif-Else Statement with an example:-

 

a = 20
b = 30
if b>a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("b is smaller than a")
b is greater than a   

From the above code it is clearly visible there should be 3 possibilities in this case and only one possibility will be true and the other two will be false at a single time. Thus, this is the reason why we are getting the desired output.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

153 Views