Decision Making in Python

In this section of the Python tutorial, we will have a look at decision making statement in Python.

In real life how do we make any decision?

We analyse the circumstances & based on that we decide what to do next. Likewise, in programming language we analyse the circumstances that exist during program execution and determine the actions taken under the conditions.

Structures of decision evaluate multiple expressions that result in TRUE or FALSE. If the result is TRUE or FALSE otherwise, you need to determine what action to take and what statements to execute.

Python’s programming language treats both non-zero & null values as TRUE, and if either zero or null, it is believed to be FALSE.

Types of Decision Making statements in Python

If statement

An if statement in the python or any other programming languages uses an expression. If the expression is True, the block of the statements under it will be executed. If it amounts to False, the block will be skipped and the control will be transferred to the statements after the block. But remember to indent the statements in a block in the same way. This is because we’re not using curly braces to delimit blocks.

Syntax of if statement in Python

if expression:
   statement(s)

If-else statement

An if-else statement in the python or any other programming languages uses an expression. If the condition is True, the block of the statements under it will be executed. If the condition is False control will be transferred to the statements compromised by else statement. But remember to indent the statements in a block in the same way. This is because we’re not using curly braces to delimit blocks.

Syntax of if-else statement in Python

if expression: statement(s) else: statement(s)

Nested if statement

There may be a situation where you want to check for another condition after the condition is true. In such a situation, you can use the nested if statement.

Syntax of nested if statement in Python

if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   elif expression4:
      statement(s)
   else:
      statement(s)
else:
   statement(s)

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart