Crus4

logo

Python if else Statement


Python if else statement are used to make decisions, about which block of code is to execute next.

The if Statement

The if statement runs a block of code when a certain condition is True or when a certain condition met.

Example

if (3 > 2): 
  print("3 is greater than 2")

Since 3 is greater than 2, the if statement will execute the block of code.

The else Statement

The else statement is used to execute a block of code if the if statement is false.

Example

if (3 > 5): 
  print("3 is greater than 5")
else:
  print("3 is less than 5")

In an above example, the if statement is not true, so the compiler will execute the else statement.

In case, if the if statement was true, then the compiler will execute the if statement and ignores the else statement.

The elif Statement

In python, the elif statement is used when we have to check more then two conditions and perform different actions based on these conditions. For example, if we want to evaluate the performance of a student based on the marks they scored in a test, we can use the following criteria:

  • If the marks are above 90, the Student’s performance is considered Excellent.
  • If the marks are between 65 & 89, the Student’s performance is considered good.
  • If the marks are between 50-64, the Student’s performance is considered poor.
  • If the marks are below 50, the Student’s performance is considered very bad.

Now in an example below let’s write a python code to figure out the performance of the student.

Example

marks = 20
if (marks >= 90):
  print ("Student's performance is Excellent")
elif (marks >= 65 and marks < 90):
  print ("Student's performance is Good")
elif ( marks >= 50 and marks < 65):
   print ("Student's performance is Poor")
else:
   print ("Student's performance is very bad")


Share This Post!

Python if else Statement

Leave a Reply

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