Decision-making statements decide the direction of the flow of program execution. Decision structures evaluate multiple expressions that produce TRUE or FALSE as an outcome. You need to determine which action to take and which statements to execute if the outcome is TRUE or FALSE otherwise.
Decision making statements available in python are:
- if statement
- if…else statement
- Nested if statements
- if-elif ladder
if statement
if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax
if (condition): statement executed if condition is True
For example:
age = 10 if age < 18: print “You are below 18 years”
Output: Here 10 less than 18 is True hence the block below the if statement is executed hence the result below.
You are below 18 years
if…else statement
We can optionally use the else statement with if statement to execute a block of code when the condition is false.
Syntax:
if (condition): # Executes this block if condition is true else: # Executes this block is condition is false
Example:
age = 20 if age < 18: print “You are below 18 years hence you are not allowed to vote” else: print “You are allowed to vote”
Output: The condition present in the if statement is false. So, the block below the if is statement is not executed and is skipped to te else statement which is executed.
You are allowed to vote
Nested if statements
Nested if statements mean an if statement inside another if statement.
Syntax
if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here
Example:
age = 19 if age >= 18: if age == 18: print “You are 18 years old” else: print “You are older than 18” else: print "You are below 18"
Output:
You are older than 18
Here, 19 is greater than 18 hence the first condition is true and the if..else statement is executed. The block in the nested if is false hence the block below the else statement is executed instead.
if-elif-else ladder
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax
if (condition): statement elif (condition): statement . . else: statement
Example:
age = 19 if age < 18: print "You are too young to vote" elif age >= 18: print 'You are 18+ hence can vote' else: print 'Please enter a valid number'
Output:
You are 18+ hence can vote