0

This might be a silly question, but I am wondering if there is a way to print or use the value being evaluated in an if statement without having to store it in a variable first before evaluating it?

something similar to this sort of syntax:

if value_of_really_long_expression == True:
    print(value_of_really_long_expression)

of course this can be achieved by:

x = value_of_really_long_expression

if x == True:
    print(x)

purely out of interest/curiosity, I am wondering if this is even possible

Derek Eden
  • 3,457
  • 1
  • 8
  • 25
  • Nope, not in the stable releases of python in any case. Though irony being, if you entered the `if` block on an `==` check, you already *know* what the expression evaluated to. However, i'm assuming this is just a glorified simplified example. – Paritosh Singh Aug 27 '19 at 12:41
  • 1
    You may be interested in this post: https://stackoverflow.com/q/11880430/4636715 . At least you can reduce to a one-liner. – vahdet Aug 27 '19 at 12:42

1 Answers1

3

It's not possible; there are no implicit references one could use. Python 3.8, though, introduces an assignment expression which at least streamlines the assignment:

if (x := really_long_expression):
    print(x)

The scope of x remains the same as if you had written

x = really_long_expression
if x:
    print(x)

that is, x is not local to the body of the if statement.

chepner
  • 389,128
  • 51
  • 403
  • 529