manyspikes

Conditions

The main conditional statement in Python is the if statement. If statements allow us to control if a particular block of code is executed or not, depending on whether an expression is equal to True or False.

Let's look at an example:

x = 2 if x > 1: print("x is greater than 1")

which prints x is greater than 1.

An if statement is constructed by using the if keyword followed by an expression (in this case, x > 1) and a colon. The code block to be conditionally executed should follow.

If x is greater than 1, the expression x > 1 will evaluate to True, in which case the code guarded by the if statement is executed. If it evaluated to False, the print statement would not be executed.

But how does Python know which of the subsequent lines of code should be regarded as part of the if block? The answer is indentation: by indenting the code by one level relative to the if statement, you are telling Python that the code is part of the preceding if block. By removing identation, you are telling Python that you no longer want the code to be affected by the if statement. For instance:

temperature = 38 if temperature > 37.5: print(f"The temperature is {temperature} degrees") print("The temperature is too high!") print("Done")

which prints

The temperature is 38 degrees
The temperature is too high!
Done

You can chain mutliple conditional checks using the elif (which stands for else if) and the else keywords.

temperature = 39 if temperature > 37.5: print("The temperature is too high.") elif temperature < 36: print("The temperature is too low.") else: print("The temperature is in the normal range.")

which prints The temperature is too high. You can also nest if statements, like so:

temperature = 41 if temperature > 37.5: print("The temperature is too high.") if temperature > 40: print("Please see your doctor.") elif temperature < 36: print("The temperature is too low.") else: print("The temperature is in the normal range.")

In a nutshell, if statements allow us to conditionally execute some code: code under an if statement is either skipped or it is executed once depending on whether or not the condition associated with the if statement is true.

The key thing to remember is that indentation is important because it defines which lines of code are inside the scope of the if statement.