Python Conditional Statements

Python Conditional Statements help you to perform different actions based on some conditions. There are the following ways to handle or use Conditional Statements in Python programming:

  1. if statement
  2. if-else statement
  3. if elif statement
  4. nested if statement

If statement

This is the easiest way to use a conditional statement. With the help of if keyword, we define the if statement.

Let’s see a simple example of Python if statement:
Suppose we want to check whether the age of a person is greater than 18.

Output of the above program is

person’s age is greater than 18

Here we have used if statement to check our condition. If our condition is matched, then python will read the print statement and will give us the output.

Note: If the condition is not matched then there will be no output or blank output. Let’s see an example:

Here we will get no Output because the condition is not satisfied.

Output of the above program is

If else statement

This way is more helpful than if statement. With the help of if and else keyword, we define the if else statement.

Example of if else statement
Let’s see a simple example of Python if else statement:
Suppose we want to check whether the age of a person is greater than 18 or not.

Here we have used if statement to check our condition. If our condition is true, then python will read the print statement and will give us the output.

Output of the above program is

person’s age is greater than 18

Note: If the condition of if statement is satisfied, then code inside the body of the if statement will be executed. However if given if condition is not satisfied then the inside the else statement will execute.


if elif statements

If we have multiple conditional statements then we can handle those statements by the help of the if elif statements.
Here is a simple example to check whether a student got first division, second division, or third division, or has failed.

Output of the above program is

enter the marks = 81
Merit


nested if statements

If a conditional statement dependent on other conditional statements then we use nested if statements. We must take care of proper indentation in the nested if statement.

Example of Python nested if statement
Here is a simple example using nested if statement to check can a student get the scholarship.

Output of the above program is

enter the marks = 98
enter the year in which you got passed 2019
you can get the scholarship



Congratulations! Chapter Finished. Do you want to practice more?
Exercises & Assignments
  • No Content Found.
  • Interview FAQs
  • No Content Found.