Battlelamb
Battlelamb

Reputation: 97

How the print function works in an if-statement condition?

A Summer Midterm question, still cannot wrap my head around it,

If someone can explain it to me I'll be glad

if print(8):
    print(10000) 

It prints 8 and i don't understand why?

Upvotes: 3

Views: 643

Answers (2)

ruohola
ruohola

Reputation: 24107

if print(8):
    print(10000) 

Things the interpreter does:

  1. Run print(8) -> you see 8 in your terminal
  2. Take the function's return value -> print() always returns None
  3. Place the return value to the condition of the if-statement
  4. Evaluate:
if None:
    print(10000)
  1. Since None is a falsy value, it will not go inside the if-block
  2. Exit the program

Upvotes: 5

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477338

An if statement will first evaluate the expression next to the if keyword. So print(8). print(8) will thus print 8 to the standard output channel, and return None.

The if statement will then evaluate the "truthiness" of that value. The truthiness of None is False. Thus means that the condition in the if condition is not truthfull, and hence the body (print(10000)) is not evaluated. It will thus print 8, but not 10000.

The documentation has a section Truth Value Testing [Python-doc]. As the documentation says:

  • constants defined to be false: None and False.

Upvotes: 3

Related Questions