Decision Making in Python

The order of execution of the statements in a program is known as flow of control. It is dependent on the programming constructs used while writing the program. Decision-making statements are used to control the flow of execution of program depending upon condition.

There are four types of decision-making statements in Python:

1. if statement

2. if-else statement

3. if-elif ladder

4. Nested if-else statement

 

if Statement

if statement is the easiest method for making a decision in Python. It simply states that if something is true, Python should perform the steps that follow. In programming, decision making or selection can be achieved through the conditional statement. The simplest form is the if statement.

 

if condition:

statement (s)

 

  1. If the condition is true, then the indented statement gets executed.
  2. The indented statement implies that its execution is dependent on the header.
  3. There is no limit on the number of statements that can appear under an if block.
  • ‘if’ is a keyword, followed by a condition and ended with ‘colon’.
  • We can use condition with bracket () also, but not mandatory.
  • A statement or statements (Block of code) are indented (usually 4 spaces) inside the ‘if’ statement and are executed only if condition evaluates to true, otherwise the control skips the block of statements inside if statement and only statement will be executed.

 

Let us look at an example to understand if statement in Python.

 

 

if-else Statement

 

‘if’ statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want the program to display some appropriate message or to execute certain set of instructions in case the condition becomes false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.

 

if-elif-else Statement

 

if-elif-else construct is used in the situations where a user can decide among multiple options. As soon as one of the conditions controlling the ‘if’ is true, then statement/statements associated with that ‘if’ are executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed, control flows from top to down.

 

Nested if-else Statement

 

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved
error: Content is protected !!