How to use IF Else in Python


Hello friends, I hope you all are doing great. In today’s tutorial, I am going to show you How to use IF Else in Python. It’s our 5th tutorial in python series. In our previous lectures, we have covered the detailed Introduction to Python and then we have also discussed Data Types in Python & How to use Strings in Python . So, now it’s time to move on a little further.
In today’s tutorial, we will cover If else statement in python and its not that difficult to understand but quite an essential one as its use a lot in programming projects. So, let’s get started with How to use IF Else Statement in Python:
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.

Let’s work with an example:

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:

Suppose I put the wrong code. It will exit the program. Now what error he will face, if he...

Top Tech News


Top