Python If-Elif-Else Multiple Conditionals Like And , Or – POFTUT

Python If-Elif-Else Multiple Conditionals Like And , Or


We have already looked if-elif-else statements in previously. if-elif-else requires conditions in order evaluate. These conditions may simple True , False or comparisons. The other way is we can define complex conditionals in order to evaluate.

Simple Conditions

Simple conditions are just single statement conditions where we do not need grouping or multiple or , and . We will just check if the value is bigger than 50 in this example.

value=55 
if(value>50): 
   print("Value is bigger than 50") 
 
#Value is bigger than 50
Simple Conditions
Simple Conditions

Multiple Conditions And Operator

The first real world usage example of multiple operators/conditions in a single if will be and operator.  We will specify different conditions and merge them together into single if to return result.

In this example we will check if the given value is less than 100 and greater than 0 . We will use greater and less than operators and merge with and operator.

if((value>0) and (value<100)):          
   print("Given number is between 0 and 100") 
 
#Given number is between 0 and 100

Multiple Conditions Or Operator

Another usage case is or with multiple conditions. We will loop different conditions and if one of them True result will be True  too. We will look if given value it not between 0 and 100 in this example.

value=-33 
if((value<0) or (value>100)):                  
   print("Given number is not between 0 and 100") 
 
#Given number is not between 0 and 100
Multiple Conditions Or Operator
Multiple Conditions Or Operator

Grouping and Precision of Operators with (..)

We have learned that we can use ( .. ) phronesis to make things more complex. Parentheses can group given conditions and provides single result result. Pharanthes can be also used to change prioritization of conditions. We will group and and or conditions in this example.

if(((value>0) and (value<100)) or ((value < 0) or (value > 100))): 
   print("This will always return True")          
 
#This will always return True

LEARN MORE  Awk If, If Else, Else Statement or Conditional Statements

Leave a Comment