Conditional Statements and Indentation in Python

In this class, we discuss conditional statements and indentation in python.

For Complete YouTube Video: Click Here

Conditional Statements

Before going into the concept. First, you should have some basics on operators and input-output. Click here.

Let’s take an example and understand conditional statements in python.

Example:

Take details of an employee and give them a bonus of 5% of their salary. If he is a manager give him an extra 8% house allowance and 5% food allowances.

Program:

conditional statements and indentation in python
Sample Program

From the above program, we understand a conditional statement is ‘if’.

In the if statement condition is given designation == “manager”. ie if the given condition is True.

It has to execute a block of code that belongs to the if condition.

The block of code is given for if conditions are.

H = salary *0.08

F= salary * 0.05

The above two lines of code are the block of code that belongs to if conditional statement.

Now we have to understand the concept of indentation.

Indentation

First, understand how python executes. Then we go to the concept of indentation.

In the above program. Python starts execution line by line. ie first line, second line, and so on.

When it comes to if statement.

If the condition is true it has to go and execute the block of code that belongs to the if statement.

How does python understand the block of code that belongs to the if statement?

For this python uses indentation.

Here we have to give at least one space at the beginning of the line.

All the blocks of statements that belong to if statement is given at least one space at the beginning.

With this space, python identifies the code that belongs to the if statement.

The remaining all lines should start in the same column.

This is how indentation helps the python compiler to identify a block of code that belongs to conditional statements.

Take one more example and understand the concept of indentation and conditional statements better.

Example:

Take details of the student and identify he is eligible for the scholarship.

If his percentage is greater than 80. He is eligible.

conditional statements and indentation in python1

After the condition colon should be a must. it’s the syntax.

The same way after else we need a colon.

If the condition is true then execute the block of code that belongs to the if statement.

If the condition is False Then go to else block of code.

The block of code belongs to if statement or else statement is following indentation.