What is a selection statement in Python?
- In some cases in programming, Our program has to decide whether the following block of codes needs to be executed or not, based on some conditions.
- Such Decision making statements/selection statements decide the direction of the flow of program execution.
- Decision making statements/selection statements available in Python are
- if (Simple If)
- if-else
- else-if ladder
- Nested if
- In python, body statements inside the selection statement are indicated by the indentation. The very first unindented line marks the end of the selection statements.
- It is a simple conditional statement that is used for decision-making.
- If the evaluated condition is true, the statements inside the if block will be executed.
- In if statement, we have only one statement to select. Because of this, it is called a One-way Selection statement.
- Syntax:
Statement 1
.......
Statement n
If-else:
Simple If statement |
Output |
- It is also a conditional statement that is used to select between two sets of statements based on the results of the evaluated condition.
- If the evaluated condition is true, then the statements inside the if block will be executed. Otherwise, the statements inside the else block will be executed.
- Since we have two statements to select based on the condition, hence it is called a Two-way Selection statement.
- Syntax:
if (condition):
Statement 1
.......
Statement n
else:
Statement 1
..........
Statement n
Else-if (elif) ladder:
If...else statement |
Output |
- A conditional statement is used to select a statement from multiple sets of statements based on multiple test conditions.
- The different test conditions are provided inside each if statement.
- If any of the evaluated conditions is true, then statement inside the corresponding if block will be executed and the control comes out of the else-if ladder.
- If none of the conditions is true, then the statements inside the else block will be executed.
- Since we have multiple sets of statements to select based on the test condition. Hence it is also called a multi-way selection statement.
- As soon as a true condition is found, the statement associated with it is executed skipping the rest of the conditions and the statements.
- Syntax:
if (condition):
Statement 1
.......
Statement n
elif (condition):
Statement 1
..........
Statement n
No comments:
Post a Comment