Beginner trying to understand functions.

Peter Otten __peter__ at web.de
Mon Dec 8 09:00:54 EST 2008


simonh wrote:

> 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:

> 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.


Generally, when you calculate something within a function you tell it the
caller by returning it:

>>> def get_age():
...     return 74
...
>>> get_age()
74
>>> age = get_age()
>>> age
74

And if you want a function to act upon a value you pass it explicitly:

>>> def check_age(age):
...     if 18 <= age <= 30:
...             print("Come in")
...     else:
...             print("Sorry, you can't come in")
...
>>> check_age(10)
Sorry, you can't come in
>>> check_age(20)
Come in

To check the age determined by the get_age() function you do:

>>> age = get_age()
>>> check_age(age)
Sorry, you can't come in

Peter



More information about the Python-list mailing list