Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 446
Battlelamb Avatar asked Jan 22 '26 10:01

Battlelamb


2 Answers

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
like image 154
ruohola Avatar answered Jan 23 '26 23:01

ruohola


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.
like image 23
Willem Van Onsem Avatar answered Jan 24 '26 00:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!