A very common yet important skill to learn in any programming language is how to write if statements. When writing an “If Statement” you specify a hypothetical condition, and state code to be executed if that condition is satisfied. This step by step tutorial is for beginners to Python to learn how to write and understand If-Statements in Python.
An if statement can be anything, such as testing if a variable is the write value, or using it in a loop for complicated programs. One simple example of the If Statement is this:
Here as shown, if loops start with the word if, then after that enter in the hypothetical statement (Such as if my name is Alaina). If you want to put an equals to in the If like I did, make sure it’s double. At the end of the statement, put a colon as shown above. This automatically puts a tab underneath the statement which is also a must.
Another feature of if statements are the ‘else’. When you have an if statement and you want your program to choose one category or another while running, it can be helpful to add an ‘else’ after the If statement.
Here, if someone didn’t enter in their age as twelve, the code would check the if loop, and see that it didn’t satisfy the requirement for it, and then immediately fall into the “else” category.
The syntax of the else is similar to that of the if; put a colon at the end and just the word else. You don’t need to specify any category because the two choices your program will have to go into is (in our case) the “is 12” category, and the “every other number that isn’t 12” category.
Finally, the last feature of the IF I’ll be talking about is the “elif”. For some people, this may be a completely new concept in any language, so let me explain.
With the previous If and else statements, you only have to cases to deal with, If a special case, and everything else, but what if we have more than two scenarios to deal with? This is when our ‘elif’ or ‘else/if’ comes into play. In this case, we will have to write something like this:
Here, instead of an automatic else, it’s almost like we’re adding another if, except it’s in the same chain of if and else.
But why can’t we just put another if? Well, when we had the if and else statement in the beginning, the if was connected to the else, so if the if statement wasn’t satisfied, it would fit into the else category, but once you start another if statement, all your code isn’t going to be as neatly connected as it can be with an elif.
You can use as many elifs as you want in a program, the only rules are that they are a lot like ifs, and your sequence of them needs to start with an if, (an elif can’t stand alone, just like a train needs an engine car at the front) and ends with an else.
I hope this tutorial helped you understand the basics of if statements. Go into the comments for any questions!