Python: The If Condition

Hello and Welcome to Blog #5, Python: If Conditions. This post will introduce the If condition in Python, how to use it, and what it is used for.



The If Condition is one of the most useful tools in any programming language. First, let's look at what is  is used for. The If Condition is used to run a line a code, If, and only If, a certain statement is True. For example, lets say that I have an array, cars, and a variable, number, which has a value of 1. I want to add an element,"Honda," to the array, but only if the value of the variable, number, is equal to 1. Here is what this whole thing would look like:

cars = ["Ferrari","Toyota"]

number = 1

I have defined the variable number and the array cars. Now, I will add "Honda" to the cars array, if 

the value of number is 1.

if number == 1:

    cars.append("Honda")

Now, I have added "Honda" to the array, because the value of number was one. As you can see, in the if condition, instead of saying, "if number = 1," it says "if number == 1:," which is just python syntax, along with the colon after the if line.  Under the if line, the line that adds "Honda" to the array is indented. This is also python syntax, and must be done if you do not want an error.


Now, lets try something else. What if the value of number was 2 instead of 1?

number = 2

cars = ["Ferrari","Toyota"]

I have defined the variable number and set its value to 2, and I have defined the array, cars.

if number == 1:

    cars.append("Honda")

This will not add "Honda" to the array. The line that adds "Honda" to the array, 'cars. append("Honda"),' is inside an if condition. The line would only run if the if statement is true, and in this case, it is not. the value of number was set to 2, but "Honda" is only added if it is equal to 1. 


This is the basic 'if condition.' However, there is a sort of 'add-on' to the if condition, 'else.' The else condition does not need to be there, but if there is a case where if something is true, then you want to do something, but if it is not true, then you want to do something else, then you would use this if-else condition. It works the same way as the if condition, as such:

if (something) == (something):

    Do something

else:

    Do something else


As you can see, the else condition is at the same indented level as the if, and it also is followed by a colon, python syntax. Anything that goes in the else is also indented four spaces. 



Thank you for reading Python: The If Condition. To understand some of the other concepts in python that were mentioned, like variables and arrays, please take a look at some of the other posts.


Please leave any comments or question in the comments section!




Comments