简体   繁体   中英

Correct approach for calling a function regardless of parameter type

I have a program that prints multiplication tables.

def print_tables(input):
    for i in xrange(1,11):
        print "%s x %s = %s" %(input, i, input*i)

user_input = raw_input("What do you want multiplied ten fold? ")

if(user_input.isdigit()):
    print_tables(int(user_input))

else:
    print_tables(user_input)

If the user enters a string "a" , I would expect the output to be:

a x 1 = a
a x 2 = aa
a x 3 = aaa
a x 4 = aaaa
a x 5 = aaaaa
a x 6 = aaaaaa
a x 7 = aaaaaaa
a x 8 = aaaaaaaa
a x 9 = aaaaaaaaa
a x 10 = aaaaaaaaaa

Calling the print_tables function in both the if and else blocks does feel a bit redundant to me.

Is there a better way in Python to call the print_tables function regardless of the parameter type?

print_tables(int(user_input) if user_input.isdigit() else user_input)

One good way is this:

if user_input.isdigit():
    user_input = int(user_input)

print_tables(user_input)

That is, have one call, but funnel the different cases into a single variable.

def mul(x, y):
    try:
        return int(x) * y
    except ValueError:
        return x * y

def print_tables(input):
    for i in xrange(1,11):
        print "%s x %s = %s" %(input, i, mul(input, i))

user_input = raw_input("What do you want multiplied ten fold? ")
print_tables(user_input)

Explanation: print_tables itself is not type-aware, that is, it doesn't behave differently on different arguments' types. It's the multiplication that should be polymorphic. So, a pythonic approach would be to make this explicit.

On a second thought, if you got a function that makes you scratch your head on how to call it, don't try to solve the problem in either way. Just eliminate that function!

def _print_table(s):
    for i in xrange(1,11):
        print "%s x %s = %s" %(s, i, i * s)

def print_str_table(s):
    return _print_table(str(s))

def print_int_table(s):
    return _print_table(int(s))

user_input = raw_input("What do you want multiplied ten fold? ")
if user_input.isdigit():
    print_int_table(user_input)
else:
    print_str_table(user_input)

As they say,

Abandon anything that gives you doubt for what gives you no doubt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM