Why does the following Python 3 "if" work?

Question:

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?

Asked By: Clive Long

||

Answers:

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

Answered By: rma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.