Click for All Topics
Imagine you see this amazing game that just launched and you approach your parents to buy you this game. Your parents agree to buy the game, but in order to get it, you need to score at least 80 percent in your upcoming examinations.
Take another scenario, you watch a particular TV series, and you are too excited to watch its new episode. The catch here is, the new episodes only release on Friday.
In the above-mentioned examples, you can clearly see that in order to do a particular task or fulfill a given desire, there is a condition added to it. To buy that game, you need to have a score of 80 percent, and to watch the new episode, you need to wait until Friday. Similarly, in Python, we have conditional statements that allow us to execute or run specific blocks of code based on whether they satisfy the conditions or not.
There are three types of conditional statements in Python. They are If, Elif (else if), and Else. The general syntax used for the above conditional statements.
if condition1:
# Code to be executed if condition1 is true
elif condition2:
# Code to be executed if condition2 is true
else:
# Code to be executed if none of the above conditions are true
Let’s use an example to understand this code in a much better way. Now, we are going to use conditional statements to check if a number is positive, negative, or zero.
x = 5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
# Output of the above Python code:
# ---> x is positive
In this example, if ‘x’ is greater than 0, the code inside the first If block will be executed and the output “x is positive” will be printed. If ‘x’ is less than 0, the code inside the elif block will be executed and the output “x is negative” will be printed.
If neither of these conditions is true, then the code inside the else block will be executed, and the output obtained will be “x is zero”.
Tip and trick:- You can also apply logical operators such as and, or, and not to combine multiple conditions within a single if statement.
x = 5
y = 10
if x > 0 and y > 0:
print("Both x and y are positive")
elif x > 0 or y > 0:
print("At least one of x or y is positive")
else:
print("Both x and y are non-positive")
# Output of the above Python code:
# ---> x and y both are positive
Conditional statements are a basic yet powerful tool in programming that enables you to create adaptive, and intelligent applications by incorporating decision-making and control flow into your code. Let’s take a look at the benefits of using conditional statements in your code.
Article written by Aakarsh Pandey, Team edSlash
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India