Conditional Statements
Introduction to Conditional statements
The conditional statements are also known as “Decision Making statements”. Python language provides the following kinds of conditional statements.
Statement | Description |
if | An if statement has Boolean expression which results either TRUE or FALSE. |
if else | If statement is followed by an else statement which is optional. When an if is evaluated to false then the else statement is executed. |
Nested statements | We can implement if statement and or if-else statement inside another if or if – else statement. Here more than one if conditions are applied & there can be more than one if within elif. |
Let us have a look on the each of the above statements.
if statement
When an if condition is true then the statements in if section are executed. Otherwise the statements which are outside of an if section will be executed.
The syntax of if statement is as follows:
Ex : A sample program on if statement
Another example of if statement is
Output
x is not greater |
if else statement
When an if condition is true then the statements in if section are executed. When the condition is evaluated to false the statements in the else section will be executed
The syntax of if else statement is as follows
Ex A sample program on if else statement
Nested if statement
A nested if is an if statement that has another if statement inside it. When if condition is satisfied then the immediate if section is executed; when the condition is evaluated to false it directly goes to the else section and the statements in it are executed
The syntax of nested if statement is as follows
Ex A simple example of nested if statement is shown in below
Output
enter a number:7
Positive number |
The elif statements/Nested if-else statements
elif is a keyword in python. It is used as replacement of else if . Whenever you want to add another condition in the same program this elif is used. It is otherwise called as Nested if-else.
The syntax of elif statement is as follows
Ex A sample program of elif statement.
The if-elif-else statement
When an if condition is true then the statements in if section are executed. When the condition is evaluated to false the statements in the else section will be executed. In the meanwhile it also evaluates the elif sections. If it results to true then it moves to next immediate elif section otherwise the execution flow transfers to the else section.
The syntax of if-elif-else statements is shown in below
Ex A sample program of if-elif-else statement
Output
Enter any number 3
True |