If... Else statements in Python

When writing your Python program, you may want a particular block of code to run only when a condition is met. If statements help you with this.

If Statement:

This tells Python to carry out an action if a condition is met. An if statement is written with the if keyword. For example:

a= 12
if a =='12':
    print('a is 12')

Let's take a look at our code. First, we declared a variable a, and assigned the value 12 to it. Then the if statement asks Python to check if the value assigned to a is 3. Since it is, it prints a is 12.

Elif Statement:

This sets another condition for Python to check if the first one was failed. For example:

a = 12
b = 12
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

First, we declared variables a, and b. Then we assigned the value 12 to both of them. Then the if statement asks Python to check if the value assigned to b is greater than the value assigned to a. Since it is not, Python proceeds to the elif statement. It checks if a is equal to b. Since it is, it prints a and b are equal.

Else Statement:

The else keyword is for anything that wasn't caught by the earlier if and elif statements. This means if the if condition and the elif condition aren't met, Python should do what is stated in the else statement. For example:

a = 12
b = 7
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("a is greater than b")

When we run this code, we see that Python prints a is greater than b. This is because the if and elif conditions aren't fulfilled so the else statement is used.

I hope you find this article useful.

Please leave a like if you do.

Zainab Lawal💛