Beginner trying to understand functions.

acerimusdux acerimusdux at comcast.net
Mon Dec 8 15:04:44 CET 2008


simonh write:
> In my attempt to learn Python I'm writing a small (useless) program to
> help me understand the various concepts. I'm going to add to this as I
> learn to serve as a single place to see how something works,
> hopefully. Here is the first approach:
>
>
>
> name = input('Please enter your name: ')
> print('Hello', name)
>
> while True:
>     try:
>         age = int(input('Please enter your age: '))
>         break
>     except ValueError:
>         print('That was not a valid number. Please try again.')
>
> permitted = list(range(18, 31))
>
> if age in permitted:
>     print('Come on in!')
> elif age < min(permitted):
>     print('Sorry, too young.')
> elif age > max(permitted):
>     print('Sorry, too old.')
>
> input('Press any key to exit.')
>
>
>
> That works fine. Then I've tried to use functions instead. The first
> two work fine, the third fails:
>
>
>
> def getName():
>     name = input('Please enter your name: ')
>     print('Hello', name)
>
> def getAge():
>     while True:
>         try:
>             age = int(input('Please enter your age: '))
>             break
>         except ValueError:
>             print('That was not a valid number. Please try again.')
>
> def checkAge():
>     permitted = list(range(18, 31))
>     if age in permitted:
>         print('Come on in!')
>     elif age < min(permitted):
>         print('Sorry, too young.')
>     elif age > max(permitted):
>         print('Sorry, too old.')
>
> getName()
> getAge()
> checkAge()
>
> I get this error message: NameError: global name 'age' is not
> defined.
>
> I'm stuck, can someone help? Thanks.
>   

You are running into Python's scoping rules. Variables in Python are not 
global by default, they are local to their scope. Each function has it's 
own scope (but blocks like if: and while: don't.) So your variable "age" 
only exists in
getage(). It doesn't exist in checkage().  You could simply add a 
"global age" statement to getAge() before you first use the age 
variable, and that will likely work.

Or, rather than declare it global, you might want to have getage() 
return a value, and then pass it to checkage () as a function parameter. 
Add a "return age" statement to getage() before "break". Then, for your def:

def checkage(age):

And then when calling:

A=getAge()
checkAge(A)




 



More information about the Python-list mailing list