Python Working With If ... Elif ... Else Conditions

Python Working With If ... Elif ... Else Conditions

Lets start working with if ... elif .. else conditions in python. if ... elif .. else allow us to take decisions. It can be nested. In some cases we may need to execute the code based on conditions. Then we use if ... elif ... else conditions in python. For example, if we wan to sort the students based on their grades then we have to use these conditional expressions(if ... elif...else).

Using "if" statement in python:

The syntax of the if condition is

if(condition):
   statement(s)

Use case: Take a number in a name/variable with some integer value and add 50 if number is less than 100 and print the resulting number.

number = 20
if number < 100:
   number = number + 50
print(number)
# Output: 70

Using "if ... else" statements in python:

The syntax of the if condition is

if(condition):
   statement(s)
else:
   statement(s)

Use case: Take a number and check if it is odd number or not(if the number is odd number if its remainder is 1).

number = 21
if number % 2 == 1:
   print("odd")
else:
   print("even")
print(number)
# Output: odd

Using "if ... elif...else" statements in python:

The elif statement allows us to check multiple conditions and execute a block of code as soon as one of the conditions are valid. we can have multiple number of "elif"statements followed by a "if" statement.

Note: elif statement is optional

The syntax of the if condition is

if(condition1):
   statement(s)
elif(condition2):
   statement(s)
elif(condition3):
   statement(s)
else:
   statement(s)

Use case: Take a student marks in a name/variable and check the student grade based on below conditions.
If marks greater than or equal to 90 grade is "A"
If marks are in between 80 and 89 (inclusive) then grade is "B"
If marks are in between 70 and 79 (inclusive) then grade is "C"
If marks are in between 60 and 79 (inclusive) then grade is "D"
If marks below 60 then grade is "F"

​​​​​marks = 80
if marks >= 90:
  grade = 'A'
elif marks >= 80:
  grade = 'B'
elif marks >= 70:
  grade = 'C'
elif marks >= 60:
  grade = 'D'
else:
  grade = 'F'
print(grade)
#output: B

Using nested "if ... elif ... else" statements in python:

We can use if...elif...else statement inside another if...elif...else statement. It is called as nested conditioning.

Use case: You have a adult website. You have to restrict users who are having age under 18 years and old people who are having age above 80 years.

age = int(input('Enter your age: '))
if age > 18:
    if x > 80:
        print('You are too old, go away!')
    else:
        print('Welcome, you are of the right age!')
else:
    print('You are too young, go away!')

Note: "input" will allow program to take data from user or keyboard at program runtime.