1

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
  • 13,811
  • 2
  • 31
  • 45
danielsore
  • 13
  • 2

2 Answers2

10

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
  • 464,258
  • 100
  • 912
  • 987
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
  • 52,115
  • 13
  • 74
  • 94