0

I am new to programming so apologies for not being able to frame the question properly but here's a more detailed version of the problem. If I run the following code:

age=2
if age:
   print("hello")
else:
   print("bye")

Output is "hello" which I read was due to age being evaluated to True.

But when I modify it to:

age=2
if age is True:
   print("hello")
else:
   print("bye")

The Output is "bye"

I was expecting the Output here to be True. Where is the gap in my understanding? I Would also be grateful if you could direct me to a link to study the topic. Thanks

  • Use `==` to compare integers by value, or `bool` to evaluate them as either true or false. See https://stackoverflow.com/questions/2987958/how-is-the-is-keyword-implemented-in-python for details on how `is` works. – Kacperito May 01 '21 at 14:19
  • https://docs.python.org/3/library/stdtypes.html#truth-value-testing – Christian K. May 01 '21 at 14:19
  • In the first code you simply check if 'age' exists. In the second code you check if age is True however age is equal to the integer 2 (so not a bool). If you check age == 2 then this is True and "hello" is printed. – John Mommers May 01 '21 at 14:20
  • @JohnMommers not if it _exists_, if it's _truthy_. – jonrsharpe May 01 '21 at 14:22
  • @JohnMommers No, the first one does not check if `age` exists. If it doesn't exist, you'll get a `NameError`. It checks if `age` has a truthy value (which for `int` values means it is non-zero). – chepner May 01 '21 at 14:33
  • Thanks. I think I understand it now. The question has been marked duplicate and so following the original question also helped me in understanding it. – rookielearner May 01 '21 at 16:23

1 Answers1

0

As per the title, yes, python evaluates objects in a boolean context when in an if.

The is keyword refers to identity, meaning that two values compared represent the same object.

Here's an article that describes it.

duckboycool
  • 2,425
  • 2
  • 8
  • 23