How to change the number of arguments in a function call dynamically in Python?

Question:

I wrote the following Python code.

def myFun(**kwargs):
    for key, value in kwargs.items():
        print("%s = %s" % (key, value))


# Driver code
a = input("Enter first word")
b = input("Enter second word")
c = input("Enter third word")
d = input("Enter fourth word")
e = input("Enter fifth word")

myFun(first=a, second=b, third=c, fourth=d, fifth=e)

As you can see that the above code takes 5 variables from the user as input and then prints them.

Now the challenge here is that if the user enters ‘Hello’ then that should not be printed.

For e.g. if suppose the third word is ‘Hello’ then "third=c" should not be present in the function call. So, the function call will look like this.
myFun(first=a, second=b, fourth=d, fifth=e)

Please note that ‘Hello’ is just an example and I can have many such words.

Besides ‘Hello’ can be present in more than one variable.
For e.g. if suppose the third and fifth word are ‘Hello’ then "third=c" and "fifth=e" should not be present in the function call. So, the function call will look like this.
myFun(first=a, second=b, fourth=d)

I cannot make any changes in the function definition.

I know I can write multiple function calls based on the conditions but is there a better way to do it?

Asked By: Anshul Gupta

||

Answers:

Call the function with a dictionary.

def myFun(**kwargs):
    for key, value in kwargs.items():
        print("%s = %s" % (key, value))

def main():
    # Driver code
    a = input("Enter first word")
    b = input("Enter second word")
    c = input("Enter third word")
    d = input("Enter fourth word")
    e = input("Enter fifth word")

    keys = ['first', 'second', 'third', 'fourth', 'fifth']

    parameters = {}
    for key, value in zip(keys, [a, b, c, d, e]):
        if value != 'Hello':
            parameters[key] = value

    myFun(**parameters)

if __name__ == '__main__':
    main()    
Answered By: Matthias