ifstatements do something when a condition is met. For example:
if x == 5: print("x is equal to 5")
You can also tell a computer what to do if the condition isn't met by using
if x == 3: print("x is equal to 3") else: print("x is NOT equal to 3")
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
elifstatements after an
ifstatement, and you can also have a final
elsestatement after all the
elifstatements, 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")
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
elseblock must be indented accordingly.
Remember: you can use an
ifstatement without an
elifstatement., but you cannot use an
elifstatement without an
ifstatement. Your code will error if there isn’t an
ifstatement to start off your
elifstatements or your
elsestatements. After all, it doesn’t make sense to say “else” or “else if” without an “if” before them.