-1

Just starting to get to know Python. Every Python expression is supposed to have a boolean value. I'm trying to verify it with simple statements, the results are a bit confusing. In principle this does not seem to have an easy logic to understand. There is something behind it that is lost to me. What could it be?

Python 3.8.0 (default, Oct 28 2019, 16:14:01) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

> foo = 1
> foo is True
False
> bar = True if foo else False
> print("{}".format(bar))
True
> 
> foo = 0
> foo is True
False
> bar = True if foo else False
> print("{}".format(bar))
False
> foo = '1'
> foo is True
False
> bar = True if foo else False
> print("{}".format(bar))
True
> 
> foo = '0'
> foo is True
False
> bar = True if foo else False
> print("{}".format(bar))
True
  • 1
    Don't use `is` here. Repeat the tests with `==`. `is` has a very particular use. – Carcigenicate Nov 14 '20 at 00:10
  • Yes...you're mixing up `True` and "truish". Many statements are "truish" in Python, but `True` is a particular value that's harder to get. You don't have to set a value to `True` to get it to have that value. The result of a boolean expression is one of the values `True` or `False`. `foo = 3; bar = foo == 3` results in `bar` being the value `True`. – CryptoFool Nov 14 '20 at 00:18
  • Check this out: https://docs.python.org/2.4/lib/truth.html. Note the use of lowercase "true" vs uppercase "True". The former, as discussed here, is what I called "truish" in my prior comment. – CryptoFool Nov 14 '20 at 00:22

1 Answers1

0

For starters, is is not the same as ==, since is is asking if it is exactly that value/object. To check if something is 'truthy' or 'falsey' (since they cannot actually be the boolean values of True or False), you can do for example:

>>> foo = 1
>>> True if foo else False
True
>>> foo = 0
>>> True if foo else False
False

>>> bar = '0'
>>> True if bar else False
True
>>> bar = ''
>>> True if bar else False
False

In general, empty lists, strings etc. and 0 are 'falsey' while most other things are 'truthy'. Maybe you would prefer the explanation here instead: https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rolv Apneseth
  • 2,078
  • 2
  • 7
  • 19