Unable to return value from 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 case, I only want to return the variable z or the value snooze. But that does not work. Please help me 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 a repeat, he grumbles too. Why is this?

+6
source share
5 answers

z is the local variable in your sleepy() function; it is not visible outside this function.

Your function returns the value z ; assign it:

 slept = sleepy(10, 0.001) print slept 

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

+8
source

You should not try to print z or snooze because they have a scope limited by the definition of the function. When you do: sleepy(10,0.001) , then the value 10 is assigned to reps , and the value 0.001 is assigned to snooze .

And then the things you want are done with these variables. In the meantime, a new variable is created with the name z with the scope within the function. And then that value returns. And as soon as the last statement is completed, all variables created inside the definition will be deleted.

So you should do:

 a = sleepy(10,0.001) print a 

This will print the value of a , which is the value you returned from within the function.

You can also print z if you declare it global, that is:

 import time def sleepy(reps, snooze): t = [] for x in range(reps): x = time.time() time.sleep(snooze) y = time.time() global z ##notice this line has been changed. z = y - x t.append(z) print 'difference = ', z*1000 print 'total:', (sum(t)/reps) * 1000 

Now the value to be returned is in z , and you can print it like this:

 sleepy(10,0.001) print z 
+2
source

When you return something from the function you are calling, the syntax is as follows:

 p = sleepy(10,0.001) print p 
+1
source

z and snooze are local variables of the function.

You need to assign the result of the function to a variable so that it is available after calling the function.

+1
source

z is a local variable. When you return z , it does not actually return the variable z , but instead returns the value that is present in z , so you need to save it in another variable and print this variable
or you can just use

 print sleepy(10, 0.001) 
+1
source

Source: https://habr.com/ru/post/947837/


All Articles