notTypecast
notTypecast

Reputation: 480

Python: Print a function which returned a value without running the function

If I try to run the following code:

def func():
    a = 5
    print 'done'
    return a
temp = raw_input('')
if temp == '':
    func()

print func()

Say temp is '' and the function is run. It prints done and returns variable a. How can I print the returned variable without running the function once more, so done isn't printed again?

Upvotes: 0

Views: 4140

Answers (2)

zyxue
zyxue

Reputation: 8888

You should assign the returned value to a variable (e.g. a).

Update: you could either print inside the function (version1) or use global variable (version2)

def func():
    a = 5
    print 'done'
    return a

# version 1: if print doesn't have to be outside of the function
def main():
    temp = raw_input('')
    if temp == '':
        local_a = func()
    else:
        # use else to avoid UnboundLocalError: local variable 'a' referenced
        # before assignment
        local_a = None
    print local_a


if __name__ == "__main__":
    main()


# # version 2: if print have to be outside of the function, then I can only
# # think of using global variable, but it's bad.
# global_a = None
# def main():
#     temp = raw_input('')
#     if temp == '':
#         global global_a
#         global_a = func()

# if __name__ == "__main__":
#     main()
#     print global_a

Upvotes: 3

kenjoe41
kenjoe41

Reputation: 260

You could use @zyxue's answer above and store the return value to a variable or you could also just not return anything from the function and just assign you final value in a function to a global variable if you have need for that. I should warn you that it isn't good practice to overuse global variables unnecessarily or overly. See: https://stackoverflow.com/a/19158418/4671205

Upvotes: 1

Related Questions