Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to return a value from a function

I have a small piece of code to understand how to return values that can be used in other sections of the code. In the following i only want to return the variable z, or the value snooze. But it does not work. Please can someone help me to understand why this will not work?

import time

def sleepy(reps, snooze):
    t = []
    for x in range(reps):
        x = time.time()
        time.sleep(snooze)
        y = time.time()

        z = y - x
        t.append(z)
        print 'difference = ', z*1000

    print 'total:', (sum(t)/reps) * 1000
    return z

sleepy(10, 0.001)

print z # does not like this.

If I print snooze it also grumbles. Why is that?

like image 448
rich Avatar asked Jun 21 '13 13:06

rich


People also ask

Why the function Cannot return the value?

Explanation: True, A function cannot return more than one value at a time. because after returning a value the control is given back to calling function.

Which function Cannot return value?

You have declared function Arrange() as void , and obviously a void function cannot return a value by definition.

Why is my function not returning a value in C?

In C there are no subroutines, only functions, but functions are not required to return a value. The correct way to indicate that a function does not return a value is to use the return type "void". ( This is a way of explicitly saying that the function returns nothing. )

How do you return a value from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.


1 Answers

z is a local variable in your sleepy() function; it is not visible outside of that function.

Your function does return the value of z; assign it:

slept = sleepy(10, 0.001)
print slept

I used a different name here to illustrate that slept is a different variable.

like image 192
Martijn Pieters Avatar answered Nov 14 '22 23:11

Martijn Pieters