How does Python determine if a value is true?

Asked

Viewed 102 times

1

I have the following doubt:

>>> a = [200,100]
>>> a[True]

Exit >>> 100

>>> a = [200,100]
>>> a[False]

Exit >>> 200

Why does this happen? The first value is false and the second true?

  • 1

    This is a C inheritance, probably. In C, false is indicated by 0, already true would be everything different from 0, often convened as 1

1 answer

7

This is because false is equal to 0 and true is equal to 1.

Then it would be the same thing:

a = [200,100]
a[1]

Output >>> 100

a = [200,100]
a[0]

Output >>> 200


In Python any value other than 0 automatically is true when you are doing some logical check, for example:

(3 == true) //true
(0 == true) //false
  • Excellent, thank you very much for the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.