Beginner trying to understand functions.

cadmuxe cadmuxe at gmail.com
Mon Dec 8 15:24:15 CET 2008


i think we should use raw_input('Please enter your name: ') instead of
input('Please enter your name: ')

2008/12/8 Peter Otten <__peter__ at web.de>

> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081208/3196f7e1/attachment.html>


More information about the Python-list mailing list