Beginner trying to understand functions.

Benjamin Kaplan benjamin.kaplan at case.edu
Mon Dec 8 09:48:27 EST 2008


On Mon, Dec 8, 2008 at 9:24 AM, cadmuxe <cadmuxe at gmail.com> wrote:

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

Print is a function in this code and range returns an iterator (or else
list(range(18,31)) is redundant). I think the OP is using python 3. Guess
we're all going to have to get used to some of the changes, like raw_input
being renamed to input.




> 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
>>
>
>
> --
> 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/1c65356c/attachment.html>


More information about the Python-list mailing list