[Tutor] Help with function scoping

Joel Goldstick joel.goldstick at gmail.com
Wed Mar 22 20:24:44 EDT 2017


On Wed, Mar 22, 2017 at 5:17 PM, Richard Mcewan <richmcewan at icloud.com> 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.
>
> 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()

You don't assign your return values above, try this:

computerGuess = generateNumber()
userGuess = getUser()

Also, you should copy and paste your full traceback when you post
here.  It will give the line number of the error
>
> #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



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays


More information about the Tutor mailing list