In many programming languages (e.g. JavaScript, C), expressions involving chained operators are evaluated differently than how we use them in mathematics.
For example, in mathematics 0 < 3 < 5
is considered as: 0 < 3
AND 3 < 5
In JavaScript the expression would be evaluated as:
0 < 3 < 5
(0 < 3) < 5
true < 5 // Type coercion
1 < 5
true
// Evaluation doesn't follow the mathematical logic we hoped
3 < 0 < 5
(3 < 0) < 5
false < 5
0 < 5
true
I only mentioned the above so that you recognize that how expressions are evaluated can vary significantly across different programming languages.
Python is one of the languages which does carry out chained comparisons similar to how we interpret expressions in mathematics.
Documentation: https://docs.python.org/3/reference/expressions.html#comparisons
So expressions like 0 < 3 < 5
will be evaluated as: 0 < 3
AND 3 < 5
.
If both comparisons are True
, then the overall expression will also be True
.
With the above in mind, your expression will be evaluated in Python as:
weight = 8.4
weight > 0 <= 2
(weight > 0) AND (0 <= 2)
True AND True
True
Therefore, the condition if weight > 0 <= 2:
evaluates as True
, and the statements in this block are executed. ppp = 1.50
is used and consequently, cost_ground
is calculated as 32.6
Instead you should write your condition as:
if 0 < weight <= 2:
This will be evaluated as:
(0 < weight) AND (weight <= 2)
The same sort of modifications need to be made to the elif
expressions as well e.g,
# You wrote:
elif weight > 2 <= 6:
# It should be:
elif 2 < weight <= 6: