Beginner trying to understand functions.

simonh simonharrison.uk at googlemail.com
Mon Dec 8 08:32:06 EST 2008


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.



More information about the Python-list mailing list