If Statements

Well, if statement is common across many programming languages.

When we have scenario, that an action should be performed only after a condition is satisfied, we can use if statement.

For example, when a person is trying to login into his gmail account, he has to give his user name and password to validate and only after validation, he will be logged in and can access his emails. Otherwise, the gmail account page will throw an error saying “Invalid User“.

Hence, the scenario will be, if (valid user) – login to gmail and allow user to see his emails.
else(invalid user) – Throw an error “Invalid User” and not allow the user to access the emails.

With this background, Let’s see how we can use this if / else statement in Python

Example:

In the example above, we have created two variables, a and b and which is assigned to value “2”.

There is a if statement that says, if a is equal to b, print the statement, “a is equal to b”.

In most of the other programming languages, you would have seen if statement is wrapped around curly braces, where in here, it is spacing.

There should be a colon (:) after the expression and if the condition doesn’t satisfies, we can use else statement as shown in the example.

Let’s see what is the output here:

Since, the condition is satisfied, the print statement is executed and displayed the message (“a is equal to b”).

Let me change the value of a to 3 and check how the program executes.

Example:

Let’s see what is the output here:

Actually, there will not be any output here. Because, the if statement failed as a is not equal to b. So, else statement will be executed.

There is pass statement in else statement, which does nothing.

Multiple Conditions:

What if we have multiple conditions to check upon.

Example:

As you can see in the above block of code, to add multiple if conditions, we use elif keyword.

There is another condition added to check if c is greater than b and a variable.

Output:

Let’s see what is the output.

Hope we have understood if statement. 🙂 You can try with your own logic to understand if statement even better.

Leave a comment

Design a site like this with WordPress.com
Get started