4.1 If, Else, and Elif Statements

If, Else, and Elif Statements


if statements do something when a condition is met. For example:
if x == 5: print("x is equal to 5")
View code on GitHub.


You can also tell a computer what to do if the condition isn't met by using else.
if x == 3: print("x is equal to 3") else: print("x is NOT equal to 3")
View code on GitHub.


You can also introduce new “if” statements when you use an “else”. These are called "else if" statements, which we write as elif. You can have multiple elif statements after an if statement, and you can also have a final else statement after all the elif statements, as shown below.
if x == 5: print("x is equal to 5") elif x == 6: print("x is equal to 6") elif x == 7: print("x is equal to 7") else: print("x is not equal to 5, 6, or 7")
View code on GitHub.
Indentation matters in Python! Indentation is useful to programmers so we can see the structure and hierarchy of the code. If you don't indent properly, your program might not run, or it might run incorrectly. In the case of if statements, whatever is inside the if block, elif block, or else block must be indented accordingly.
Remember: you can use an if statement without an else or elif statement., but you cannot use an else or elif statement without an if statement. Your code will error if there isn’t an if statement to start off your elif statements or your else statements. After all, it doesn’t make sense to say “else” or “else if” without an “if” before them.

Previous Chapter

Next Section

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.