Sometimes in programming languages, we have the same situations then it has t be decided which block of code should be executed based on a condition. Decision-making is a prime feature of any programming language. It allows us to make a decision, based on the result of any given condition. It’s involved in order to change the sequence of the execution of statements, depending upon given conditions. In this method, some set of statements with conditions is provided to the program. Python Decision-making is best for this type of situation.
Python Decision-making structures evaluate multiple expressions which produce TRUE or FALSE as result. You need to determine which action to take and which statements to execute if the result is TRUE or FALSE otherwise.
Three main python decision-making statements are defined below,
Statements | Description |
if statements | An if statement consists of a boolean expression followed by one or more statements, which results are either TRUE or FALSE. |
if…else statements | An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE. |
nested if statements | You can use one if or else if statement inside another if or else if statement(s) |
If Statement:
An if statement consists of a Boolean expression followed by one or more statements, which results are either TRUE or FALSE.
Syntax,
#if statement v1 = 50 if v1 < 100: print ("V1 is less than 100")
If-Else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression is FALSE.
Syntax,
#if else statement v1 = 50 v2 = 100 if v1 > v2: print ("V1 is Greater") else: print ("V2 is Greater")
Nested-If Statement:
You can use one if or else if statement inside another if or else if statement(s).
Syntax,
#nested if statement x = 10 if x >= 0: if x == 0: print("Zero") else: print("x is greater than 0") else: print("x is less than 0")
Single Statement Suites:
If the suite of an if clause consists of only a single line, it will go on the same line as the header statement.
Example of a one-line if clause:
#one-line if clause variable = 50 if ( variable == 50 ) : print ("The value of a variable is 50") print ("Python Programming")