简体   繁体   中英

How to call a function with return value inside an if statement in python

I have two functions with one containing a return statement. My agenda is when the first function executes in the if condition, compiler is throwing a syntax error.

Here's my script.

def hi():
  return 10,20

def hello(a):
  if a:
    print "asd"

if a,b=hi() : hello(a)

The error is thrown at "=" in the if condition. How to solve this. Or is there any alternative to perform this in one liner?

You need to create a tuple of a and b then you can compare using ==

Use this,

if (a,b)==hi() : hello(a)

Here is the full code which prints asd

def hi():
  return 10,20

def hello(a):
  if a:
    print "asd"

a,b = 10,20

if (a,b)==hi() : hello(a)

You can't have arbitrary expressions in an if statement, you can only use a boolean like value (something that can be interpreted as true/false).

So you need to do something like this

def hi():
  return 10,20

def hello(a):
  if a:
    print "asd"

a, b = hi() 
if a:
    hello(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM