[Tutor] Help with function scoping
alan.gauld at yahoo.co.uk
Wed Mar 22 20:41:09 EDT 2017
On 22/03/17 21:17, Richard Mcewan wrote:
> I'm expecting two functions to be defined. Then called.
And thats what you've got. But...
> One returns a random number. The other user input (guessing the number).
And thats also what you've got but you don't do anything
with the returned value you just ignore it.
You need to assign the result to a variable.
> I expect the return values to act like variables that I can use in a while loop.
The return values are just values like any other.
Just as you can do
x = 42 # assign the value 42 to the variable x
you can also do
y = myFunction() # assign return value from myFunction to variable y
> ...The error report says 'NameError:The name 'userGuess' is not defined.
Which is true, you use it but you never assign a value to it.
You need to do something like:
userGuess = getUser()
Although the name is poor since you are not getting
the User you are getting a number...
> My understanding is wrong somewhere.
You are confusing values and variables.
Variables in Python are labels that we attach to values
(aka objects) so that we can refer to those values later
in our code.
> I thought functions would allow me to return values
> I could use elsewhere without having to define them
They return values. But you need to assign those
values to variables to be able to use them.
> initially. I.e. Encapsulation.
None of this has anything to do with encapsulation.
Functions encapsulate an algorithm and the data needed
to perform that algorithm, they return a value without
you needing to know how the value was worked out.
That is encapsulation.
> I've looked for other examples but get the same issue.
The simplest examples are the built in functions,
such as pow() or len()
Doesn't do anything(*) because we throw the result away.
L = len('freddy')
assigns the return value from len() to the variable L.
> I expect a function to return a variable I can use elsewhere.
No, functions return values not variables.
You create the variables because its you
that will use them. How could the function possibly know what
you want to call the variable? It cannot, it just returns
the result of some operation or calculation. Only you know
what you are going to use that for, so you can create a
variable with a suitably descriptive name.
> In the case below I'm not sure how I can use the work of the function elsewhere.
Just assign it to a variable. Then use the variable.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor