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")
	print("x is NOT equal to 3")

View code on GitHub.


You can also introduce new if statements when you say else, and keep on adding them. These are called "else if" statements, which we write as elif

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")
	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.

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.