Beginner trying to understand functions.
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Tue Dec 9 08:50:58 EST 2008
simonh a écrit :
> Thanks for the extra tips Ivan and Bruno. Here is how the program
> looks now. Any problems?
>
>
>
> import sys
>
> def get_name():
> name = input('Please enter your name: ')
> print('Hello', name)
This one would be better spelled "get_and_display_name" !-)
> def get_age():
> try:
> return int(input('Please enter your age: '))
> except ValueError:
> print('That was not a valid number. Please try again.')
> return get_age()
Warning : there's a recursion limit in Python. While there are very few
chances you hit it in this case, it may bite you one day if you start
using recursion instead of iteration.
> def check_age(age,min=18,max=31):
> if age < min:
> print('Sorry, too young.')
> elif age >= max:
> print('Sorry, too old.')
> else:
> print('Come on in!')
>
> def again():
> response = input('Try again? Y or N: ')
> while response != "Y":
You probably mean 'if response != "Y"' ?
> if response == 'N':
> print('Program finished.')
> input('Press any key to exit.')
> sys.exit()
> else:
> return response
This return value is never used in the calling code. And if the user
types anything else than "Y" or "N", the program will exit without even
a goodbye message.
> run()
> def run():
> get_name()
> a = get_age()
> check_age(a)
> again()
As far as I'm concerned, I'd write it that way:
def read_string(question, error=''):
if not error:
error = "That was not a valid string. Please try again."
while True:
result = input(question).strip()
if result:
return result
else:
print error
def read_int(question, error=''):
if not error:
error = "That was not a valid number. Please try again."
while True:
try:
return int(input(question).strip())
except ValueError:
print(error)
def check_in_range(obj, mini, maxi, if_ok=0, if_lesser=-1, if_greater=1)
if obj < mini:
return if_lesser
elif age >= max:
return if_greater
else:
return if_ok
def again(question="Try again ?", yes="Y", no="N"):
# XXX : see appropriate string formatting for Python 3
# in 2.x, I'd write it as:
# prompt = "%s (%s or %s): " % (question, yes, no)
prompt = question + " " + yes" + " or " + no + ": "
while True:
response = input(prompt)
if response in (yes, no):
return response == yes
def run():
name = read_string("Please enter your name: ")
print("Hello, ", name)
age = read_int("Please enter your age: ")
messages = {
0: "Come on in!",
-1: "Sorry, too young",
1: "Sorry, too old",
}
message_key = check_in_range(age, 18, 31)
print(messages[message_key])
def main():
while True:
run()
if not again():
print('Program finished.')
input('Press any key to exit.')
return
if __name__ == "__main__":
main()
NB : the 'if __name__ == "__main__"' will allow you to use your code as
both a script (ie : calling it as 'main' program) or as a module
(importing it from within another script or module so you can reuse the
functions), by only calling 'main()' if the file is used as a script.
HTH
More information about the Python-list
mailing list