If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.
Syntax:
if (condition): code1 else: code2 [on_true] if [expression] else [on_false]
Here we’ll study how can we check multiple conditions in a single if statement. This can be done by using ‘and’ or ‘or’ or BOTH in a single statement.
Syntax:
if (cond1 AND/OR COND2) AND/OR (cond3 AND/OR cond4): code1 else: code2
The following examples will help understand this better:
PROGRAM 1: program that grants access only to kids aged between 8-12
age = 18 if ((age>= 8) and (age<= 12)): print("YOU ARE ALLOWED. WELCOME !") else: print("SORRY ! YOU ARE NOT ALLOWED. BYE !")
Output:
SORRY ! YOU ARE NOT ALLOWED. BYE !
Program 2: program that checks the agreement of the user to the terms
var = 'N' if (var =='Y' or var =='y'): print("YOU SAID YES") elif(var =='N' or var =='n'): print("YOU SAID NO") else: print("INVALID INPUT")
Output:
YOU SAID NO
PROGRAM 3: program to compare the entered three numbers
a = 7 b = 9 c = 3 if((a>b and a>c) and (a != b and a != c)): print(a, " is the largest") elif((b>a and b>c) and (b != a and b != c)): print(b, " is the largest") elif((c>a and c>b) and (c != a and c != b)): print(c, " is the largest") else: print("entered numbers are equal")
Output:
9 is the largest
Not just two conditions we can check more than that by using ‘and’ and ‘or’.
PROGRAM 4:
a = 1 b = 1 c = 1 if(a == 1 and b == 1 and c == 1): print("working") else: print("stopped")
Output:
working