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?
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.
You have declared function Arrange() as void , and obviously a void function cannot return a value by definition.
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. )
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With