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.
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:
# 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 . The output of the program is given below.
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 or . There are two set membership operators
- not in
In this example, we are going to use operator to check if a value belongs to a list or not.
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 and if not found returns . If found returns a . You will print the result based on the output you get.
Python has special function associated with different data types or for testing certain conditions. They are called because the return either or . Consider the following code which checks if a string is digit or not.
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
The Boolean operators can check multiple conditions at a time and return either or . There are three which are given below.
# 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