-1

I often have code similar to

a = somefunction()
if a:
    do_something()

Is there in Python a construction which would blend the initialization with the condition test? Something like

if a = somefunction():
    do_something() 

which would test a after it has been assigned a value via somefunction()?

WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

3

No, there is no way to do this; an if statement must have a condition- so putting an assignment in it will cause a SyntaxError. Your first example is the best, but unless you need a again later then this:

if somefunction():
    do_something()

Should suffice.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • Thanks. The first example works fine, I just wanted to reduce the possible clutter (and I need `a` afterwards) – WoJ Oct 26 '14 at 13:53
  • @WoJ Glad I could help. When the grace period has passed, would you mind accepting with the tick to show that the issue is closed? Thank you. :) – anon582847382 Oct 26 '14 at 13:54