Basic relational operators question

I am confused about how relational operators in computer programming are different to those in maths. This is a very basic question but I am only just getting started with programming as a major beginner.

See the following statement:

if weight <= 2:

price_per_pound = 1.50

elif weight <= 6:

price_per_pound = 3.00

elif weight <= 10:

price_per_pound = 4.00


price_per_pound = 4.75

My question is this. Say weight = 4.
4 is less than 6, but it is also less than 10.
So weight = 4 works for the idea that weight <= 6, but weight 4 can also work for the idea that weight <= 10.

From using this if/elif/else statement in a programme, I have learned that if I passed in weight = 4, this would apply to the weight <= 6 statement, and price_per_pound would equal 3.00.

Why does weight = 4 fall into the weight <= 6 category only? Why can’t it also have been equal to weight <= 10?

You need to remember that the Python interpreter won’t evaluate all the conditional statements you have. It will start at the top with the if and if it fails, it will move to the next elif and if it fails, the next and the next until all the evaluations are done.

With this is mind, when you have weight = 4, you already know that if weight <= 2: will fail but that elif weight <= 6: will evaluate to true. At that point the code inside that elif is execute and the rest of the conditional tree skipped!

1 Like