Conditions in Python help to execute code based on certain conditions and can be useful in cases when you need to validate user input, such as password creation, it can be used in games, to handle various likely scenarios, control user flow on an application, and so on. This article will teach you about conditional covering if condition, if else statement, Elif, Nestedelif, and use cases.
Conditional if
Conditional operations deal with executing a block of one or more statements if a certain condition is true.
# syntax
if condition:
python executes this code if condition is true.
Example 1: Let's say you need to buy a book and you need 200 dollars, and the only way to buy is if you have the exact price, now use the if condition to allow buyers to buy only if they have 200 dollars.
Book_price = 200
if customer_balance = 200:
print('You have enough fund to buy the book!')
If Else Statement
The if condition is checked and executed only if it is true, if not the else condition is returned.
color = 'red'
if color == red:
print('This is red')
else:
print('This is not red')
The code assigns the value 'red'
to the variable color
. It then checks if the value of the variable color
equals the string 'red'
.
If the condition is true, it prints the message 'This is red'. Otherwise, it prints the message 'This is not red'.
If Elif Else
x = 5
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
When the variable x
is set to 5, the program checks if x
is greater than 10. If it is, the program prints x is greater than 10
. Otherwise, if x
equal to 10, it prints x is equal to 10
. If neither condition is met, the program prints x is less than 10
.
Nested Elif Else
#lets look at standard nested Elif
if condition1:
# add code to execute if condition1 is true.
elif condition2:
#add code to execute if condition 1 is false, and condition2 is true
elif condition3:
#add code to execute if all conditions above is false
else:
#add code to excute if all contidions above is false
You can also add as many elif as you need, logical operations such as and
, or
, and not
can be combined to explore more complex conditions.
day ="Saturday"
if day == "monday":
print("Wear blue dress")
elif day == "Tuesday":
print ("Wear a green dress")
elif day == "Thursday":
print ("Wear a purple dress")
else:
print("Wear a shirt")
Conclusion
So far we have explored various conditionals in Python, it is important to note that the code within a condition is indented, and it also helps to show which code block belongs to the conditional statement.
Conditions make a program more robust, allowing codes to be executed when certain criteria are met.
Let me know in the comments if you enjoy reading this article. I write about data analysis, tools, and interesting projects you would love to try.