In previous articles, we have seen how to write your first Python program, using Range() function, Len() function, for loops and other programs. In this article, we will see how we can write a conditional statement using IF-ELSE in Python.
If else is generally used for decision making, means to run a particular code block on the basis of criteria. In Python, decision making is done on the basis of if statement, if-else statement and nested if statements. These are also known as Conditional Statements.
Table of Contents
if statement:
If the statement is used check the specific condition if the particular condition is true then the if block will execute.
Example: In the above code, if a condition is a true means a is smaller than 10 then the print (“condition will “) will run.
if(a<10):
print("condition is valid")
if-else statement:
if-else statement is used to check the condition and take action if the statement is true and false. Suppose if a condition is not correct at that time we can run another block of code, at that time you can use else statement. So, if the condition ist true run this code block else run different code block.
Simple Example:if
print("condition is valid")
else:
print("not a valid condition but you want to run the code then you can write your code here")
Another Example:a=10
b=20
if(a<b):
print("a is greater")
else:
print("b is greater")
nested if:
nested if statements do the same this as if-else, the condition check but it can check the multiple conditions like if 1 condition fails it will check another condition if the second condition fails it check another, it means you can check as many conditions as you want.
Example:
a=10
if(a==10):
print("a is equal to 10")
elif(a==20):
print("a is equal to 20")
else:
print("a do not matches")
That’s it Folks on this topic. We will see do some practice exercise of these conditional statements in our next article. Let us know your comments on this article in the comment box below. Kindly like our Facebook page, follows us on Twitter and subscribe to our YouTube channel for latest updates.