In expressions that use both the 'and' and 'or' operator, the 'and' operator is evaluated first.
This is used in situations where you have 2 or more sets of conditions and either one or some of the conditions needs to be true/false to execute an instruction.
e.g consider we have 3 conditions , condition1, condition2 and condition3 and condition4. And we want to do something if both condition1 and condition2 is true or if condition3 and condition4 is true.
This can be written as
if ( (condition1 and condition2) or (condition3 and condition4)) :
If you need the or operator to be evaluated first, use parentheses, just as you would in any mathematical expression.
Lets write a programme to allow a person to sit in flight. For normal citizen a person should have valid ticket and checkin only then he is allowed to sit in flight, for a pilot person doesnot need any of these.
hasValidTicket = True isSecurityCheckDone = True isPilot = False if ( hasValidTicket and isSecurityCheckDone or isPilot ) : print("Is allowed to enter") else : print("Is not allowed to enter")
An expression of values combined with or produces the first true value, where as expression of values combined with and produces the last true value.
print("Value of 10 or 20 or 30 is " , 10 or 20 or 30) print("Value of 10 and 20 and 30 is ", 10 and 20 and 30)
Find the Output :
x = 15 y = 12 z = 23 print(x>10 and y>9) print(x>17 and y>10) print(x>23 and y>13) print(x>20 and y>30 and z<30)
Write a programme to check if a child can enter a show . The rules of the entry are
1. should have valid ticket
2. should be wearing formal sleeves dress
3. A child can enter show on childrens day without satisfying rule 1 and 2.
hasValidTicket = True
isWearingFullSleeves = True
IsChildrensDay = False
if( ( hasValidTicket and isWearingFullSleeves) or IsChildrensDay ):
print("Child can enter")
print("Child cannot enter")