""" Do single parameter math calculations with prompting
optionally converting degrees to radians"""

import math
    input = raw_input
    # Python 2, input is replaced by raw_input like in Python 3
    # no raw_input -> Python 3, input has correct definition -> do nothing

lookup = dict((func,math.__dict__[func])
              for func in math.__dict__
              # let's take out special __ starting functions
              if not func.startswith('__'))

while True:
    a = input("""
Enter function or
empty input to quit
? for list of functions:
        func = lookup[a]
    except KeyError:
        if not a:
        elif a == '?':
            print('Available functions are:\n\t'+'\n\t'.join(lookup)+'\n')
            print("%r is not a legal function choice!" % a)
        if  hasattr(func, '__call__'):
            print('\n%s\n' % func.__doc__)
                args = input('Give parameter for %s: ' % a)
                if args:
                    args = args.split(',')
                    args = [float(arg) if '.' in arg else int(arg) for arg in args]
                    if 'radians' in func.__doc__:
                        args = args if input('Convert degrees to radians (Y/n)?').lower().startswith('n') else map(math.radians, args)
                    print (func(*args))
                    # function without parameters
            except ValueError as e:
            except TypeError:
                print('Wrong number of parameters for %s' % a)
            print('Variable %r has value %s' % ( a, func))

IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

It is adapted to include multiple parameters and checking of when radians conversion is apropriate from docstring, among other improvements. Little hurried it through as you can see prompting for parameter instead of 'appropriate number of parameters' and the old docstring in beginning, like I wrote.

It is good idea to finalize the code for some responses (maybe generalize little) and post them as code snippets if they could be helpful for somebody in future.

I wanted to post some new code for the holidays and to celebrate 2000 posts mark, which does not show actually in post count in my postings, but you can see in my info page. For some reason they are out of sync.

Edited 6 Years Ago by pyTony: n/a