Python – Decision Making(Conditional Statements)
Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.
Statement & Description |
if statements An if statement consists of a boolean expression followed by one or more statements. Syntax The syntax of the if.. statement is − if expression: statement(s) Example days = int(input(“How many days in a leap year? “)) if days == 366: print(“You have cleared the test.”) print(“Congrats!”) |
if…else statements An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE. if expression: statement(s) else: statement(s) Example answer = input(“Are You Graduate? Yes or No >> “).lower() if answer == “yes” : print(“Great…. Go for Higher Education”) else : print(“You should go for Graduation at least.”)print(“Thanks!”) |
The elif Statement The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. syntax if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s) Example if response == 100 : print(“You have cleared the test.”) break elif response == 150 : print(“You have cleared the test.”) break else : print(“Your guess is wrong. Please try again.”) 4. Nested if Statements You can use one if or else if statement inside another if or else if statement(s). if (condition1): # Statements Executes when condition1 is true if (condition2): # Statements Executes when condition2 is true else : # Statements Executes when condition2 is false else : # Statements Executes when condition2 is false Example : To find greatest among 3 numbers. a = int(input(“Enter 1st Number”)) b = (int(input(‘Enter 2nd Number’))) c = int(input(“Enter 3rd Number”)) if a>b : if a>c: print (“%d is greatest ” % (a)) else : print (“%d is greatest” % (c)) else : if b>c : print (“%d is greatest” % (b)) else : print (“%d is greatest” % (c)) |