Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying an 'if' statement with bool()

I have some code that causes Pylint to complain:

The if statement can be replaced with 'var = bool(test)' (simplifiable-if-statement)`

The code (with obfuscated variable names) is below.

A = True
B = 1
C = [1]
D = False
E = False

if A and B in C:
    D = True
else:
    E = True

print(D, E)

How can this be simplified so that Pylint does not throw any errors?

I don't quite understand how bool() can be used for this. I know it converts any value to a Boolean value, but I don't know how it can be applied here.

like image 972
Gary Avatar asked Mar 29 '18 02:03

Gary


People also ask

Can you use a boolean in an if statement?

An if statement checks a boolean value and only executes a block of code if that value is true . To write an if statement, write the keyword if , then inside parentheses () insert a boolean value, and then in curly brackets {} write the code that should only execute when that value is true .


2 Answers

That logic can be expressed as:

D = A and B in C
E = not D
like image 170
Stephen Rauch Avatar answered Oct 16 '22 21:10

Stephen Rauch


Try this:

D = bool(A and B in C)
E = not bool(A and B in C)
like image 42
ndmeiri Avatar answered Oct 16 '22 19:10

ndmeiri