I´m a 1 week self taught python3 guy, and i´m into the comparison and boolean operators and learn this:
True and True True
True and False False
False and True False
False and False False
So, i call
print(3 < 4) and (6 < 5)
True + False
So, why do i get True
?
I have tried all other booleans trying to make some similar error, changing the way i enter this (<
) sign, entering this line in python tutor and the result is the same, and makes me think 6 is minor then 5 some how, so i think i´m not looking at what should i look and it´s gonna be embarrassing to know the answer. Thanks.
Because you aren't printing (3 < 4) and (6 < 5)
, you are printing 3 < 4
.
When calling a function, you may recall that you use parenthesis to provide arguments to the function. For example:
print("Hello world")
Will print Hello World
because that is the argument provided to it.
Similarly, when you invoke the print
function with 3 < 4
– this expression is in fact true.
When you say:
a and b
Python checks to see if both a
and b
are true. So if you do:
print(3 < 4) and (6 < 5)
a = print(3 < 4)
and b = (6 < 5)
False
You said that the expression evaluates to True
. But that is not actually correct. The expression evaluates to False
because (6 < 5)... but you only print out 3 < 4
.
Python was created to be a simple, clean, and readable language. By adding unnecessary symbols and tokens to the code, you obfuscate it. This leads to less readable code and can lead to many mistakes, such as yours.
Always avoid using parenthesis where not needed. You could have accomplished the same thing by writing:
print(3 < 4) and 6 < 5
However, you meant something totally different. You meant to write:*
print(3 < 4 and 6 < 5)