shailesh mishra shailesh mishra - 3 months ago 7
Python Question

Boolean expressions with and /or statements in python

I am having a small problem implementing a simple and or logic in python. Here is an example

a = 1
b = 0
c = 1


i am looking for a True/False output using and/or logic. If i do

a == b and c


The output is

False


But if i do

a == b or c


The output is

1


Here I want the output return as True statement. How can it get it?

Answer

and and or aren't strictly Boolean operators. They treat operands in a Boolean context, but don't implicitly convert them to Boolean values. If you want a boolean value, do the conversion explicitly.

a == b or bool(c)

Be sure you are using Boolean constants where they are relevant. If c only ever gets a value of 0 or 1, then use False and True directly, instead of encoding Boolean values as integers (like in C).

Comments