By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
While writing a program, most of the time we face a situation where we have to make a decision.
Decision making is anticipation of conditions that could occur while execution of a program and there is a need to specify some actions according to those conditions. In a decision making structures, there is a condition which is either a single expression or multiple expressions.
This condition when evaluated produce either TRUE or FALSE as outcome. Based on the outcome, we need to determine which action to take and which statements to execute.
Refer the figure below to understand it clearly. FALSE TRUE
Above is the general form of a decision making structure that is found in most of the programming languages including Python.
In Python programming language, it should be noted that any non-zero and non-null values are assumed as TRUE, however if it is either zero or null, in that case it is assumed as FALSE value.
Following are the types of decision making statements in Python language.
Statement
Description
if statements
An ‘if’ statement consists of a boolean expression which generally follows either one or more statements.
if...else statements
An ‘if’ statement can be followed by an optional else statement. When the boolean expression is TRUE then the statements in ‘if’ block are executed and if it is FALSE then the statements in ‘else’ block are executed skipping the statements present in ‘if’ block.
Nested if...elif...else statements
Nested ‘if’ statements are ‘if…elif…else’ statements within other ‘if’ statement.
Syntax for if and if…else statement. Below is the syntax for if statement alone in Python language.
if expression: statement(s)
Below is the syntax for if…else statement alone in Python language.
if expression: statement (s)
else:
statement (s)
Python code example on if…else statement
Python Code example to demonstrate Nested if-elif-else statement. Below is the syntax of the nested if...elif...else construct may be:
if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s)
elif expression4: statement(s)
else: statement(s)
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.