Complex Comparisons
In the last article we looked at very basic example of if
else
and elif
statements. However things can get a little more complex than that depending on your program's functionality.
Let's have a closer look to start this off.
Let's introduce something called Reynold's number Re. When studying the flow of some fluid inside of a pipe:
- If Re is between 2000 and 10000, then the flow is transitional
- If Re is smaller than 2000, then the flow is laminar
- If Re if bigger than 10000, then the flow is turbulent
let's execute some code that demonstrates if the flow is transitional or not:
Using multiple comparison operators
reynolds_number = 5000 if 2000 < reynolds_number < 10000: print("The flow is transitional")
>> The flow is transitional
The code above checks if Re is between 2000
and 10000
. You can use multiple comparison operators in the same statement to do so.
Using logical operators
The example above can also be done using logical operators:
reynolds_number = 5000 if reynolds_number > 2000 and reynolds_number < 10000: print("The flow is transitional")
>> The flow is transitional
The code above renders the same result as the last example. However, this time we use the logical operator and
to determine the condition. We checked if Re is bigger than >
2000
and
if Re is smaller than <
10000
.
change Re to 11000
. Now if you run the code, nothing should be executed, since and
requires both conditions to be true. and Re is not smaller than 10000
.
Let's also use the or
operator to determine if the flow is not transitional:
reynolds_number = 1000 if reynolds_number <= 2000 or reynolds_number >= 10000: print("The flow is not transitional")
>> print("The flow is not transitional")
The above code checks if Re is smaller or equal than <=
2000
or
if Re is bigger or equal than >=
10000
. We chose a Re, which satisfies the first condition. Since or
only requires one of the conditions to be True. The code below it will execute.