简体   繁体   中英

How can i print and return a value from a function in python?

i cant figure out how to make a return value from a function return and print, Example

def exe(a,b):
    if a == b:
        return 1

How would i get that 1 to print as well as return? Thanks in advance. I know its a stupid question and pretty useless, but im pretty sure it can be done and not knowing how is driving me nuts.

You can have multiple statements, but the "return" ends the function.

Print is just a statement when combined with the expressions (the stuff to the right of it) (in Python 2) that sends to expressions to standard out, (stdout), typically the console. In Python 3, print is a function, and so it's preferable to use print as a function in modern Python.

So you want print to come before return.

def exe(a,b):
    if a == b:
        print(1)
        return 1

Check this code

def exe(a,b):
    return 1 if a == b else None

print exe(1,1)

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