1

I was doing a quick test on the "if" statement and the following code fragment results in the print producing output as expected.

Case 1

x = True
if x:
    print("Roses are red")

Results in >>> Roses are red, in the interpreter

Also:

type(x)
>>> <class 'bool'>

As expected.

Then I tried:

Case 2

x = "True"
if x:
    print("Roses are red")

Again I got the result: Roses are red

and :

>>> type(x)
<class 'str'>

Can someone explain in the second case why the "if condition is satisfied" (if that is an appropriate way to describe the situation) and the print() is executed?

I would have thought the correct operation would be something like

if <expression>:
    <do this>

where "do this" is executed only when "expression" evaluates to the Boolean value True. Why is "do this" executed when "expression" is a string?

gd1
  • 11,300
  • 7
  • 49
  • 88
Clive Long
  • 286
  • 2
  • 12
  • 2
    https://docs.python.org/3/reference/datamodel.html?highlight=__bool__#object.__bool__ – gd1 Jul 11 '17 at 19:15

1 Answers1

2

The string "True" is truthy meaning that it evaluates to true in your if condition.

rma
  • 1,853
  • 1
  • 22
  • 42