Home /Python/Python IF Statements

Python IF Statements

IF Statements

In the heart of programming logic, we have the if statement in Python. The if statement is a conditional that, when it is satisfied, activates some part of code. Often partnered with the if statement are else if and else. However, Python's else if is shortened into elif. If statements are generally coupled with variables to produce more dynamic content. Let's cut to an example really quick.

Example

a = 20 if a >= 22: print("if") elif a >= 21: print("elif") else: print("else")

Result: else

So, we have the variable a that equals twenty. Now, we run it through our if statement that checks to see if a is greater than or equal to 22. It isn't. So, we skip past the inner print statement and continue to the elif statement. This conditional checks if a is greater than or equal to 21. It isn't either, which brings us to the final leg of our expanded if statement. The else is the catch all, which means if the previous conditionals are not satisfied, we will run the code inside it. So, we run the print("else"), and we see in the results, the string else.

The If Syntax

The most important thing you might have missed in the example above is how Python's syntax is a lot cleaner than other languages. However, this also means it is very picky and tends to bite beginners with errors. After every conditional we have a colon. Next, you must proceed to a new line with 4 spaces to tell Python you only want this code with 4 spaces to be run when the previous conditional is satisfied. Ok, well it doesn't have to be 4 spaces, but you must be consistent with the spaces you use to indent. You can use 3 every time if you want, but 4 is kind of a standard. Also, if you wanted to run more than one statement after the conditional is satisfied, you must have a new line with the same number of spaces before the next statement.