If Else Statement in Python

Here is another common conditional in Python. We use this one when the condition of a program is needed or can be either True or False. Hence, you will specify what the computer will do when True and also when False. That is why there is an if and an else. That is telling the computer that if this happens, do this. If this doesn’t happen, do that.

When the condition is True, the statement inside the if block is executed; if the condition is false, the statement in the else block is executed.

We write the if…else statement in Python like this:

a = 245
b = 39

if b > a:
    print ("b is greater than a")
else:
    print ("b is not greater than a")

Now, we can think back to my friend looking for a job and me. My friend has two conditions he wants the new position to fulfill, or else he will decline and let me have it.

That means we will combine the two conditions with an and keyword.

When you are out and between two conditions in Python, you tell the computer that both needs must be met. It is not a matter of if one is completed, then do this.

Let us take an example. We got our first job, but the company only promised only 2 days’ vacation in a month. Let us write this code block in the Visual studio code:

salary = 5300
vacation = 2

if salary > 500 and vacation > 2:
    print ("I will take the job")
else:
    print ("This job is shit. I don't want it.")

Did you see that? Even though one condition is True, the other wasn’t, and so the computer filed it as False.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials