9

IF-ELSE CONDITIONS

by

The Education Machine

[support@theeducationmachine.com]

We have already seen flavour of conditions while studying COMPARISON operators. Now, we will see what action to perform if condition is met or not met.
True or False are returned when an expression is compared or evaluated. I hope you know what an expression is.
Try using help() function to read more about if condition -> help('if')
Once we write a condition using if keyword, if block is started:

if __ :
      print("If condition in if statement is True")
elif __:
      print("If condition in elif statement is True")
else:
      print("If condition is not met in either if or elif")

Every condition should be ended with a colon (:).
All the statements under the conditional statement should be indented.
There can be only 1 if & else statement in a if-else block. But there can be multiple elif statements inside a same if-else block.

We created a variable - eid, then check if value assigned to the variable is equal to 10 or not, using "if" condition and print the value using f string.

  eid = 10
  if eid == 10:
      print(f"Employee ID is {eid}")


Output:
Employee ID is 10

"If" condition is the 1st condition which needs to met ,if not, then print the statement which is under "else" condition. In below code, we have taken age as 22, and then applied few conditions on it i.e.If the age is greater than or equal to 18, then you are eligible and 1st print statement will be printed. If 1st condition is not met then, 2nd print statement will be printed.

  age=22
  if age >= 18:
      print("You are eligible to apply for Voter ID")
  else:
      print("You are not eligible to apply for Voter ID")


Output:
You are eligible to apply for Voter ID

To apply more than 1 condition using if, elif and else.

  age=6
  if age >= 18 and age <= 40:
      print("You are eligible to apply for Voter ID")
  elif age < 18:
      print("You are not eligible to apply for Voter ID")
  else:
      print("You have given incorrect age"))


Output:
You are not eligible to apply for Voter ID

Try it yourself:
Create a string variable to accept your city as value.
-- Use if-else condition to check if the city is matching with the city in the if statement, then print a message for user. Else, print some other message under else statement.
1.) Try using comparison operators.
2.) Try using Identity operators.

Let's use input() function to take user's age as user input. This will throw an error because comaprison is not possible between a string and integer.

  age = input("Enter your age: ")
  if age >= 18:
      print("You are eligible to apply for Voter ID")
  elif age < 18:
      print("You are not eligible to apply for Voter ID")

reserved_keywords

Let's check the datatype of age.

  print(age, type(age))


Output:
24 <class 'int'>

Now, let's solve the problem of the above cell using int() function.
Since input() always takes values as string.

  age = int(input("Enter your age: "))
  if age >= 18:
      print("You are eligible to apply for Voter ID")
  elif age < 18:
      print("You are not eligible to apply for Voter ID"))


Output:
Enter your age: 24
You are eligible to apply for Voter ID

To create variables - conditionally.

Let's use input() function to take user's monthly salary as user input. Here, the user wants that if the monthly salary is greater than 10,000 then ctc will be equals to monthly salary multiplied by 12. And if the monthly salary is less than 10,000, then ctc will be equals to (monthly salary multiplied by 12) plus monthly salary i.e. bonus.

  mon_salary = int(input("Enter your monthly salary: "))
  if mon_salary >= 10000:
      ctc = mon_salary * 12
      print(f"Your annual CTC is: {ctc}")
  elif mon_salary < 10000:
      ctc = (mon_salary * 12) + mon_salary           # bonus for lower earning group
      print(f"Your annual CTC is: {ctc}")


Output:
Enter your monthly salary: 9600
Your annual CTC is: 124800

Elif condition can be applied as many time as user wants to, as shown below:

  mon_salary = int(input("Enter your monthly salary: "))
  
  if mon_salary < 10000:
      print("1st case")
      ctc = (mon_salary * 12) + mon_salary          # bonus for lower earning group
      print(f"Your annual CTC is: {ctc}")
  elif mon_salary >= 10000 and mon_salary < 40000:
      ctc = (mon_salary * 12) + (mon_salary/2)
      print(f"Your annual CTC is: {ctc}")
  elif mon_salary >= 40000 and mon_salary < 80000:
      ctc = mon_salary * 12
      print(f"Your annual CTC is: {ctc}")
  else:
      ctc = (mon_salary * 12) - mon_salary
      print(f"Your annual CTC is: {ctc}\nYou are earning TOO MUCH!")


Output:
Enter your monthly salary: 90000
Your annual CTC is: 990000
You are earning TOO MUCH!

Check if given name is in the list or not.
Instead of elif statement, else would also work here.

  names = ['Modi', 'Yogi', 'Kejriwal', 'Shah']
  name = input("Enter your name: ")
  
  if name in names:
      print(f"Welcome {name} to the night club")
  elif name not in names:
      print(f"{name}, your name is not in the guest list, GO HOME!")


Output:
Enter your name: Modi
Welcome Modi to the night club

Instead of creating a list variable, user can directly pass list to if statement.
Instead of elif statement, else would also work here.

  name = input("Enter your name: ")
  
  if name in ['Modi', 'Yogi', 'Kejriwal', 'Shah']:
      print(f"Welcome {name} to the night club")
  elif name not in names:
      print(f"{name}, your name is not in the guest list, GO HOME!")


Output:
Enter your name: verma
verma, your name is not in the guest list, GO HOME!

Let's do some gambling -> may be roulette!

  num = int(input("Enter your lucky number: "))
  win_num = 16
  
  if num == win_num:
      print(f"Congrats!, you are millionaire now (in dreams)")
  elif num != win_num:
      print(f"You failed to become a millionaire")


Output:
Enter your lucky number: 16
Congrats!, you are millionaire now (in dreams)

To solve above question using multiple elif conditions

  num = int(input("Enter your lucky number: "))
  win_num = 16
  
  if num == win_num:
      print(f"Congrats!, you are millionaire now (in dreams)")
  elif int(num) - win_num in range(0,3):
      print(f"You failed to become a millionaire but you are very close to the winning number")
      print(f"Winning number is {win_num - int(num)} away from your guess")
  elif int(num) - win_num in range(-3,0):
      print(f"You failed to become a millionaire but you are very close to the winning number")
      print(f"Winning number is {win_num - int(num)} away from your guess")
  else:
      print("You are wasting your time in casino, better GO HOME!")


Output:
Enter your lucky number: 16
Congrats!, you are millionaire now (in dreams)

Input function will take 3 values from user separated by "," which will be stored as a tuple. If we do not split the tuple, then the whole tuple will get stored in all the 3 variables. Now, to unpack tuple to store individual values to respective variables, we have to use split method which would have "," as delimeter, as shown below:

  name, age, designation = input("share your name, age and designation separated by comma(',')").split(",")
  
  if int(age) >= 18 and designation in ("MANAGER","DIRECTOR","CONSULTANT"):
      print(f"Welcome to this meeting {name}")
  else:
      print(f"You are not eligible to attend this meeting {name}")


Output:
share your name, age and designation separated by comma(',')a,25,MANAGER
Welcome to this meeting a