How to use IF Else Statement in Python
- IF Else Statement in python takes a Boolean Test Expression as an input, if this Boolean expression returns TRUE then code in IF body will get executed and if it returns FALSE, then code in ELSE body will be executed.
- You can understand it better by looking at its Flow Chart in right figure.
- Here's the syntax of IF Else statement in python:
if number == 10: print(number) else: print('Number is not equal to 10"
- We use if, in our daily life, it is part of our conversation, most of the time.
- For example, I say, If I win a lottery then I will go to a world tour! If I clear the test then I will throw a party.
- Here's another example, that if you are working late hours let say, overtime duty then you will get extra money, else you will not get the extra money.
- Suppose, we have a food chain and our customer has a voucher for it.
- He has a voucher number (which is a code) written on it, by showing it, he can get a discount or he can get a free meal.
- If he is providing a correct secret code, then he will get a free meal offer. Otherwise, he will not be able to avail any offer.
- So, let's design this simple code using If Else statement:
Offer = 500 (This is, by default, price of a meal)
- We will take the input from the user.
voucher_number = input("please enter your voucher number: ")
- Whatever the number he will enter, it will get stored in that "voucher_number".
- Now let's check if the code, that he has entered is correct or not.
- We will need to use the IF statement here and first let's add this condition:
if voucher_number=="9753":
- If the voucher number is matching with the company generated number, then the offer will be:
offer -=300
- If the code is correct then deduct the amount as a discount.
- Then print("congratulations, you have got a discount")
- Then print("your remaining offer has " + str(offer))
- Run the program
- See the image, it says to enter the voucher number in the output window:
- We will use else statement for this, if the condition is not correct.
- I have simply printed the message in else body, as shown in below figure:
Relational Operators in Python
As we are discussing IF Else statement, so we should also have a look at relational operators in python:- Relational Operators are used to find a relation between two variables or data packets.
- We use relational operators in test expressions of IF Else statements.
- We have five types of Relational Operators i.e.
- Greater than >
- Less than <
- Greater than equals to >=
- Less than equals to <=
- Equals to ==
- Let's understand them with an example. Now I have to check which number is greater so I will write it as: