Kayla Budzeak
2 min readJul 3, 2021

--

Are you ready for conditionaaaaaaaaaals?! *think of this coming across the loudspeakers in a voice something akin to older wrestling days*

That’s right everyone; it has come time for if/else statements. For those that have studied another programming language before this will end up being very familiar territory, and potentially syntax depending on your background.

So let’s start with the basics. If/else statements are a version of flow control, where we can control how our code functions by creating these ‘decisions’ based on true or false conditions; i.e. If my dog is hungry, then I’ll feed them. In Python, these statements make use of colons : and indentations or whitespace.

Syntax:

If Statement:
if some_condition:
#execute some code
If/Else Statement:
if some_condition:
#execute some code
else:
#do something else
If/Else If/Else Statement:
if some_condition:
#execute some code
elif another_condition:
#do something different
else:
#if no condition(s) are true do something else

As you can see with the above syntaxes we can build off of an initial if statement to include as many or few conditions as we need for our code to operate the way that we intend. Let’s look at some examples:

In the above example, we have passed in an argument of the variable a. Now a can be defined somewhere else in our code, and then passed into our function for evaluation. With this being a simple boolean if/else a can simply be either True or False. If we wanted to create something a little more complex, like if we had a friend over at our home, we write something like this:

If our friend is at our home, our program would change their ‘status’ to ‘Not Here’ and tell them “Goodbye”, otherwise it will change their ‘status’ to ‘Here’ and tell them “Hello”. Now, this doesn’t take into account any timing like we normally would in real life, but I believe it is a great example of an if/else statement. Another great example is feeding an animal/pet; if they’re hungry feed them, and if not don’t feed them.

Hopefully, this helps to further cement your understanding of if/else statements, not only in Python but in general terms as well!

--

--

Kayla Budzeak

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.