So far you have learned about different structures of conditional. But the conditionals such as if-then-else also employ different types of logical operators. In this article, you will learn about the conditionals and operators that we can use with conditional structures. There are categories of logical operators that the python programming language uses and they are :
- Relational Operators
- Set Membership operators
- Boolean Functions
- Boolean Operators
Now we see examples of each one them and understand how it works.
Relational Operators
The relational operators are those operators that return true or false after comparing numeric or non-numeric values. To learn more about relational or logical operators visit the following link:
Example Program:
# Check the mark of a student and display the result marks_average = 60 if marks_average >= 50: print("You have passed the Test") else: print("You failed! Try harder next time")
The program uses “greater than or equal to” (>=) operator to evaluate the
You have passed the Test
Set Membership Operator
The set membership operator checks if a particular value belongs to a set or not. The set could be anything that represent a
- in
- not in
In this example, we are going to use
my_fruits = ["Oranges","Apples","Grapes","Banana","Mango"] # now check if "Apples" in the fruit list or not if "Apples" in my_fruits: print("Apples in the list") else: print("Not in the list")
The set operator will check each item with
Boolean Functions
Python has special function associated with different data types or for testing certain conditions. They are called
str = "23444" if str.isdigit(): print("This string is digits") else: print("This is string")
The output of the program is given below.
============== RESTART: C:/Python_projects/Boolean_Functions.py ============== This string is digits
Boolean Operators
The Boolean operators can check multiple conditions at a time and return either
- and
- or
- not
# In the example, we check the price of cake which must be less than $100 # and must contain chocolate, if true you can buy them, else not buy them # =================================================================== cake_price = 90 contains_chocolate = True # =================================================================== # check the conditions using Boolean operator AND # =================================================================== if cake_price < 100 and contains_chocolate == True: print("Go ahead, buy the cake") else: print("Don't buy the cake")
Output of the program is given below.
======== RESTART: C:/Python_projects/Boolean_Operator_Cake_Example.py ======== Go ahead, buy the cake