In the last tutorial, you have learned about Operators in Python. So, we will talk about the Decision Making in Python now.
Decision making in Python
Decision making in Python includes the if statement, the if-else statement, the elif statement, and the nested if statement. You may wonder, why we call it decision making? Since a programmer uses it to control the flow of the program, hence it falls under the category of decision making.
The if statement
In decision making, the first condition is the if statement. An if statement, checks for the condition, if the condition is true then the body part of the if statement will execute. On the other hand, if the condition evaluates to false, the body part of the if statement will not execute.
The flow diagram shows the working of the if statement as shown below.
The syntax of the if statement is:
The syntax of if statement
Henceforth, the above syntax very clearly states that an if statement works like this, if the condition is true then Statement[s] is executed, else not. Probably, the statement may be a single statement or multiple statements.
Example of the if statement
Write a program to display whether a person is eligible to vote
The output of the above example
if… else statement
Next in decision making is the if… else statement. In an, if… else statement, if the condition is true, the body of the if statement will execute. On the other hand, if the condition is false, the body of the else part will execute.
Flowchart of an if… else statement
The syntax of the if… else statement is
The syntax of the if… else statement
The above syntax very clearly states that, if the condition is true the body of the if executes else, the body of the else will execute.
Example of the if…else statement:
Write a program to display greatest of two numbers using if… else statement
In the above example, a and b is initialized with 10 and 20 respectively. As a result, it checks for the condition a>b. Since a is not greater than b therefore, it will display that b is greater than a.
The output :
Another condition is the if…elif statement. An if…elif statement allows to check multiple conditions for True and execute the body of the if block as the condition is true. If the condition is false, it checks for the condition of elif block and will execute the statements defined below. Else, it will go to the next elif and as stated above the process continues. If none of the condition is true, then the else block will execute.
Flowchart of if..elif statement
Example of the if…elif statement:
Write a program to display the entered number in words.
Nested if..elif..else Statement
An if..elif..else within the other if..elif..else statement is called nested if..elif..else statement.
The syntax of nested if…elif…else
Example of the if…elif…else statement:
Write a program to demonstrate the nested if…elif…else statement