The if statements in Python is a condition that must be fulfilled in order for a desired command to be executed. All programming is based on conditions. It is the if-statements that control the dependent conditions, which gives the foundation for all logic in programming
The if statement in Python tests if the logical expression (if-condition in the image) is fulfilled. The logical expression is a condition that is either true or false. For example, if you press a lamp button, the lamp should either be turned on or off. Not both at the same time. With an if kit, you can decide whether to turn the power on or off (depending on whether the lamp is off or on).
The picture to the right shows how the program starts and arrives at the If condition. If the If condition is fulfilled then the program proceeds and performs one or more operations, but if the condition is not fulfilled then the program skips the operations and proceeds.
It is possible to use one or multiple conditions that indicate if there are one or multiple operations to be performed.
The If statements in Python is easily created by using the reserved word If
if (logical expression): Operation / Operations …
To be extra clear, in our code above
if (logical expression):
Initiates the if statement, and
Operation / Operations ..
Is the operations that we want to perform when the logical condition is met.
Note, the code on line three is indented and therefore part of the if statement, if we would stop indenting the code, those parts of our code would not be included in the if statement
Below is an example of how an if statement works.
run_operation = True if(run_operation): print("If statement has started") print("All operations that are indented will be performed") print("This command is not included in the if statement because the code is not indented")
The result in this case will be:
If statement has started All operations that are indented will be performed This command is not included in the if statement because the code is not indented
However, if we instead set the variable run_operation to False, then the code inside the if statement will not be performed
run_operation = False if(run_operation): print("If statement has started") print("All operations that are indented will be performed") print("This command is not included in the if statement because the code is not indented")
The result will be:
This command is not included in the if statement because the code is not indented
If we want to check if an integer variable is within an interval, for example, between 0 and 200, we easily set up the if statement with the logical expression.
num = 50 if(num > 0 and num < 200): print("Number:", num)
And in this case we get the result
For more technical and specific information about the If statements in Python we recommend the Python docs website