If Else statements are used as a form of conditional programming which is something that you probably do every day in the real world. In this article, I’ll show you some examples of If-Else with Python programming language.
Introduction to If Else Statements
The If-Else statements are conditional statements which are the statements you need to decide whether you are going to have tea or coffee or to decide whether you will have toast or a muffin for breakfast, etc. In each of these cases, you make a choice, usually based on information such as I had coffee yesterday, so I will have tea today.
Also, Read – 100+ Machine Learning Projects Solved and Explained.
In Python, these choices are programmatically represented by conditional if-else statements. In this construction, if a condition is true, then the action of If is performed, possibly if it is not true, then another action of Else can be performed instead.
If Else Examples with Python
In this section, I will take you through some examples of If Else statements with Python. Below are the 3 examples of If Else statements that we will cover:
- Body Mass Index Calculator
- Calculating Discount on Sale
- Checking Eligibility for voting
Body Mass Index Calculator:
Height=float(input("Enter your height in centimetres: ")) Weight=float(input("Enter your Weight in Kg: ")) Height = Height/100 BMI=Weight/(Height*Height) print("your Body Mass Index is: ",BMI) if(BMI>0): if(BMI<=16): print("you are severely underweight") elif(BMI<=18.5): print("you are underweight") elif(BMI<=25): print("you are Healthy") elif(BMI<=30): print("you are overweight") else: print("you are severely overweight") else:("enter valid details")
Enter your height in centimetres: 160
Enter your Weight in Kg: 50
your Body Mass Index is: 19.531249999999996
you are Healthy
Calculating Discount on Sale:
amount = int(input("Enter Sale Amount: ")) if(amount > 0): if amount <= 10000: discount = amount * 0.05 elif amount <= 15000: discount = amount * 0.12 elif amount <= 20000: discount = amount * 0.20 else: discount = amount * 0.30 print("Discount: ",discount) print("Net Payable Amount: ",amount-discount) else: print("Invalid Amount")
Enter Sale Amount: 55000
Net Payable Amount: 38500.0
Checking Eligibility for Voting:
age= int(input("Enter your Age : ")) if age >=18: status= "Eligible" else: status="Not Eligible" print("you are",status,"for vote.")
Enter your Age : 67
you are Eligible for vote.
I hope you liked this article on If Else examples with Python programming language. Feel free to ask your valuable questions in the comments section below.