3

I’m reading a value from a General Purpose IO (GPIO) configured as Input and it returns a string that is either 0 or 1. I see two easy ways to convertiing it to boolean:

bool(int(input_value))

or

not not int(input_value)

Which is most Pythonic? Are there more Pythonic ways then the ones presented above?

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
danielsore
  • 33
  • 3

2 Answers2

12

There are many ways, but I would like to propose the following:

{'0': False, '1': True}[input_value]

This has the advantage of raising an exception if you ever get a value different to what you expect (because of a bug, a malfunction, an API change etc).

All the other options presented thus far will silently accept any string as input.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

If your input_value must be "1" or "0", and you want your boolean value to be true if it is "1", then you want the boolean expression

input_value=="1"

E.g.

bool_var = (input_value=="1")

This will give True if input_value is equal to "1", and False if it is equal to "0" (or anything else).

khelwood
  • 55,782
  • 14
  • 81
  • 108