[Tutor] Help with function scoping
Mats Wichmann
mats at wichmann.us
Wed Mar 22 20:20:03 EDT 2017
On 03/22/2017 03:17 PM, Richard Mcewan wrote:
> Hi
>
> I wonder if you can help.
>
> I'm confused about how functions should work. Below is some code I write to check my understanding.
>
> I'm expecting two functions to be defined. Then called. One returns a random number. The other user input (guessing the number).
>
> I expect the return values to act like variables that I can use in a while loop.
>
> The programme asks for the user input then crashes. The error report says 'NameError:The name 'userGuess' is not defined.
>
> My understanding is wrong somewhere. I thought functions would allow me to return values I could use elsewhere without having to define them initially. I.e. Encapsulation.
>
> I've looked for other examples but get the same issue. I expect a function to return a variable I can use elsewhere. Not sure how to do. In the case below I'm not sure how I can use the work of the function elsewhere.
You mention "scoping", so... a variable defined in a particular scope is
not visible outside that scope. That's fine, because you then return it,
but what you're returning is the value, not the variable. You need to
save that value. The "simple fix" is to assign the function returns to
the variables you want, see below:
> Advice welcome.
>
> Richard
>
> Using Pythonista App on iOS with Python 2.7 on iPhone 5s
>
> # coding: utf-8
> import random
>
> #guess number game
>
> #computer generates random number
> def generateNumber():
> computerGuess = int(random.randrange(0,101))
> return computerGuess
>
> #get user
> def getUser():
> userGuess = int(input('Guess a number'))
> return userGuess
>
> #call for computer and user
> generateNumber()
> getUser()
# try this:
computerGuess = generateNumber()
userGuess = getUser()
# note these two names in the global scope are not
# the same as the identical names in function
# scopes, but there is no clash either, because
# of scoping rules
>
> #loop to check guess and report
> while userGuess != computerGuess:
> if userGuess < computerGuess:
> print('Too low')
> getUser()
> elif userGuess > computerGuess:
> print('Too high')
> getUser()
> elif userGuess > computerGuess:
> print('Correct!')
>
> #Add counter of guess later
>
>
> Sent from my iPhone
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list