On Tue, Aug 7, 2012 at 4:37 AM, Peter Otten <__pete...@web.de> wrote: > Dane Saltzman wrote: > >> I'm new to python and I was wondering if you could tell me how I would: >> >> first, define a function,distance_from_zero, with one parameter (choose >> any parameter name you like). Second, have that function do the following: >> 1. Check the type of the input it receives. >> >> 2. If the type is int or float, the function should return the absolute >> value of the function input. >> >> 3. If the type is any other type, the function should return "This isn't >> an integer or a float!" > > I'm assuming that the subject line is a hint from your professor where you > should look for functions that > > (a) check if a value is of a particular type > (b) calculate an absolute value > > I suggest that you scan the table at > > http://docs.python.org/library/functions.html > > for candidates and try to come up with a suggestion for the implementation > of distance_from_zero() yourself. Come back with the code you have if you > run into problems. We will be glad to help you fix them. > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor
This looks like homework. So, I'll let Peter's response stand as what looks like good advice to answer your question. While you can do it that way, and that way seems to be what your instructor wants you to learn, among python programmers there is a saying that its better to ask forgiveness than permission. Try to do something, and if it raises an error, take some other action. If you open up a python shell you can experiment: >>> abs(-3) 3 4.5 >>> abs(-5) 5 >>> abs (1, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: abs() takes exactly one argument (2 given) >>> abs('b0b') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'str' >>> With this knowledge you can do something like this: def distance_from_zero(value): try: return abs(value) except TypeError: return "Sorry, can't find an abs of a type like that" Rather than testing if you can find an absolute value of the type you pass (there maybe other types that you want to use later) for instance complex numbers also have distance values: >>> abs(complex(3,4)) 5.0 -- Joel Goldstick _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor