Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Python Conditional Statements

Python Conditional Statements

July 17th, 2019

Python Conditional Statements

The if…elif…else statements are conditional statements that are used to carry out decision making processes in Python. It can be used to follow a specific logic where conditions are set and used for evaluating data. Often, in real-life scenarios, a program may have to skip over a sequence of codes and choose between different sets of codes. To choose the right set of codes to execute during the decision-making process, comparison operators are commonly used. Comparison operators are used to compare values during the decision-making process to check whether it meets a certain condition or not. Python Conditional Statements

IF Statement Python

The if statement is declared using the “if” keyword followed by the test expression or condition and ends with a colon to close the heading. The body of the if statement is indented right below it and stops right before the next unintended code. It is possible to have multiple lines of code inside the indented body. The indented body will only be executed when the condition is true. In the example below, the value 6 is assigned to x. When the program runs, it will first check the if condition to see if the condition is true. In the example below, if x is equivalent to 1, then the condition would be true. However, x is equivalent to 6 and not 1, therefore, the body of if statement is ignored or skipped and moves on to check for the next condition. However, since there is no alternate condition it will proceed to run the next unintended statement. As the following unintended statement is not part of a condition, it will be printed. if statement
I am not part of the body of if statement so I will print In case you have only one statement to execute, you can add the statement in the same line as the if statement.

x = 5;

if x == 5: print(“x equals to 5”)

Output:
x equals to 5

IF-ELSE Statements Python

An if-else statement is used to include an alternate condition. It will first evaluate the condition for the if statement and if it is true, it would execute the codes within its body. But, if the if condition is false, the body of else will be executed. The blocks between an if-else statement can be separated by using indentations within each body. In the following example, the if condition is false since the value of x is not equivalent to 1. Therefore, it skips to the next unintended block which is the else statement in this case. When none of the conditions are met in the previous conditions, the body of else statement is executed by all means. However, if the if condition were true, the else statement would not be executed. if else statement

Output:
Not 1
If there is only one statement each for if and else statement, it can be added on the same line as shown below:
x = 8
y = 20
print("X") if x > y else print("Y")
Output:
Y

IF-ELIF-ELSE Statement Python

The elif condition can be used when multiple conditions need to be set. If the condition for if statement happens to be false, it moves on to the next elif block. A multiple number of elif blocks can be used in between an if and else block for setting various alternate conditions. If none of the conditions are true, then the else block will be executed. In the following example, “mango” is set as the value for favorite_fruit. In this case, it first checks through the if condition and since it is false, it moves on to the first elif block. Since this condition is also false, it moves on to the next elif block. As none of the conditions are met or are true, it moves on to execute the else statement.

favorite_fruit = "mango"
if  favorite_fruit == "apple" :
print ("Apple is my favorite fruit!")
elif favorite_fruit == "peach":
print ("I love peaches!")
elif favorite_fruit == "cherry":
print ("Cherries are amazing!")
else:
print ("I can eat a ", favorite_fruit,  "for every meal")
Output:
I can eat a mango for every meal

Nested IF Statements Python

It is possible to have an if-elif-else statement within an if statement or even within an elif statement. This is known as nesting. There can also be more than one level of nesting so by following proper indentation, the level of nesting can be determined. However, it is not recommended to use many levels of nesting as this can get confusing. A nesting can be used when there are conditions within a condition. So for instance, when a condition is found to be true, it can have more conditions within its body. Nesting can be used as a way of filtering results to get even more specific results. The example below uses nested condition to evaluate the user’s age and print an output based on the age. If the user enters an positive integer, the condition is true and it further continues to evaluate the condition within its body. Based on the user input, if the user is below 18 years, “Very young” would be printed. Otherwise, if the user is below 60 years but above 17, “Adult” would be printed. If the user is above that age, “Senior Citizen” would be printed in the output. If the user enters a negative number, it does not meet the if condition and so moves to the else block which would be executed.

Example 1:
age = float(input("Enter your age: "))
if age >= 0:
if age < 18:
print("Very young")
elif age < 60:
print("Adult")
else:
print("Senior Citizen")
else:
print("You have entered a negative number. Please try again")
However, do note that in a case like this, the sequence of the condition is also very important. Let’s look at the same example with a change in the order of the condition to better understand this. For instance, if a user gives the input for age as 15, the output would be “Adult” instead of “Very young”. Logically, since the if condition is evaluated first, it falls into a more general category and the elif statement would never be evaluated.

Example 2:
age = float(input("Enter your age: "))
if age >= 0:
if age < 60:
print("Adult")
elif age < 18:
print("Very young")
else:
print("Senior Citizen")
else:
print("You have entered a negative number. Please try again")
In such a case, you can follow the logic of the first example or you can choose to use the second example by adding logical operators (and, or, not) to set more than one condition within a block. As you can see, two conditions have been specified within the if condition using the AND operator to indicate that if the age is between 18 to 60 years, “Adult” should be printed. Otherwise, if the age is less than 18, “Very young” should be printed ensuring that it meets the primary condition where age >= 0. As such the output for the first and third example is the same.

Example 3:
age = float(input("Enter your age: "))
if age >= 0:
if age >= 18 and age < 60:
print("Adult")
elif age < 18:
print("Very young")
else:
print("Senior Citizen")
else:
print("You have entered a negative number. Please try again")
In addition to comparison operators, logical operators can also be used to set more specific conditions.
There are 3 types of logical operators:

  • AND operator
  • OR operator
  • NOT operator

nested if Statement

AND Operator

For a condition to be true, both the operands need to be true. In this example, the if condition implies that only if the user is female and is over 40 years old, then the condition is found to be true. In this case, the condition returns false despite the gender being female as the criteria for age is not met where age needs to be above forty. So, it moves on to the next block but the condition is false again as it does not meet the gender criteria. Hence, it proceeds to the else block which is rendered true since all the preceding conditions are false.

gender = "F"
age = 32
if gender == "F" and age > 40:
print("Female over 40 years")
elif gender == "M" and age < 40:
print("Male below 40 years")
else:
print ("Male or female below 40 years")
Output:
Male or female below 40 years

OR Operator

The OR operator is less strict as compared to the AND operator because unlike the AND operator where both operands need to be true to return true, an OR statement requires only one operand to be true to return true. In this example, if the weather is either hot or dry, it would print “Summer”. Otherwise, if it is either cold or chilly, it would print “Winter”.

weather = "cold"if weather == "hot" or weather == "dry":
print("Summer")
elif weather == "cold" or weather == "chilly":
print("Winter")
Output:
Winter

NOT Operator

A NOT operator is used to reverse the result where if the result is true, then it returns false and vice versa.

x = 5print(not(x > 2))
Output:
False
The sequence of if-elif-else statements should always be in order: it starts with an if statement and may sequentially require additional clauses like elif and else depending upon the conditions the developer needs to set. For instance, a condition may be set where “if” a person is 18 years or older, they can vote for the elections “else”, they are not allowed to vote. So logically, when the program runs, it would first look at the condition of the if statement and only if the condition is true (meaning, the condition has been met), it would execute the codes within its body and ignore the other conditions. However, if the if condition is false (meaning that it has not been fulfilled), an elif (meaning, else if) and else statement would be the alternate conditions. Note that without an if statement preceding an elif and else statement, there would be an error in the output generation.
age = 59if age >= 18:
print ("You are eligible to vote for the upcoming elections!")
else:
print ("Sorry but are not eligible to vote since you are under age")
Output:
You are eligible to vote for the upcoming elections!