DECISION STRUCTURES
Need for Decision Structures
• An algorithm is a complete sequence of actions to solve a problem if
followed exactly. Algorithms are built using three basic building
blocks: Sequence, Selection, and repetition.
• Sequence: A control flow where the statements are executed in a
progressive order, without decisions or repetition.
• Selection/Decision or Branching: A decision is made like condition
checking to decide the execution of one or more statements.
• Iteration/Repetition or Loop: A loop is one or more instructions the
computer repeatedly performs.
Forming Conditions
• In Python, the conditions are test expressions. The outcome of the
test expression may be two or more outcomes. The decision depends
upon the variables’ values or test expressions.
• Test Expressions can be, A Boolean Value, Expression involving
relational operators> Expressions that the logical operators combine.
• There are three types of statements, if, if-else, and if-elif.
Conditions using a Boolean Variable
• Illustration of Boolean Variable.
Illustration of bool function in Interactive shell.
Illustration of Relational Operators Illustration of Chained Condition
if-Statement
if-statement is one of the simplest forms of the decision control statement. It is a selection control statement that
tests a test expression or a condition and executes a statement or many statements (Suite) based on the condition
• The syntax of the one-way decision statement can be given as,
Illustration of if-statement in Interactive
mode
The if-else Statement
This is done by a two-way decision statement known as if-else. In this statement, If the condition is not satisfied,
an alternative statement or suite specified by else is executed
• The syntax of if-else is as follows,
Illustration of if-else statement
Inline if-statement
• An inline if-statement is a convenient form of representing an if-else
statement. This is also known as the ternary operator. This statement
allows one to execute conditional if statements in a single line.
• The General inline statement is given as follows,
If-elif statement
Illustration of if-elif statement
Nested-if conditions
Instead of using multiple if statements, it is possible to place one if-statement inside another if –statement.
This is known as nested-if statements.
• Finding a maximum of three numbers Let us consider one more example. Let us try to implement the
following algorithm for finding the largest of the three numbers. The python script is self-explanatory and is
given below: