Beginner trying to understand functions.

Pierre-Alain Dorange pdorange at pas-de-pub-merci.mac.com
Mon Dec 8 08:57:02 EST 2008


simonh <simonharrison.uk at googlemail.com> wrote:

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

Indeed age was not a global... So :

1/ make it a global (just define "age=0" before getAge()

2/ or return a value from getAge() and pass this avlue to checkAge.

I recommand the second option, less globals is always better.

def getAge():
    while True:
        try:
            age = int(input('Please enter your age: '))
            return age

        except ValueError:
            print('That was not a valid number. Please try again.')

def checkAge(age,min=18,max=31):
    if age in list(range(min, max)):
        print('Come on in!')
    elif age < min:
        print('Sorry, too young.')
    elif age > max:
        print('Sorry, too old.')

getName()
a=getAge()
checkAge(a)

For my part, i wouldn't loop getAge(à this way : i dislike infinite
loop.
I prefer to return None when ther is an error and check for None in the
main program

def getAge():
    try:
        age = int(input('Please enter your age: '))
        return age

    except ValueError:
        print('That was not a valid number. Please try again.')
        return None

getName()
a=getAge()
if a!=None:
    checkAge(a)

of i you want to loop in getAge() :

def getAge():
    age=-1
    while age<0:
        try:
            age = int(input('Please enter your age: '))

        except ValueError:
            print('That was not a valid number. Please try again.')

    return age

I'm a beginner with python, perhaps it was not "pythonic", but i'm sure
someone will tell is it's not.

-- 
Pierre-Alain Dorange        <http://microwar.sourceforge.net/>

Ce message est sous licence Creative Commons "by-nc-sa-2.0"
        <http://creativecommons.org/licenses/by-nc-sa/2.0/fr/>



More information about the Python-list mailing list