Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

How do I accept variable length arguments for multiplication program, I can pass the parameters with the function name, however, I don't know how to accept the input from the user.

I have used *argvs to accept any number of arguments. I have tried taking value from the user inside the for loop so that n number of arguments can be passed but it is not working. I know the code is not correct but I don't know how to do it.

Here's some code :

def mul(*nums):

    result = 1

    for n in nums:

            #nums = int(input("Enter the Numbers to be multiplied : "))

            result *= n

    return result 

#print(mul(4,5,4,4))

 print(mul(nums))

Expected - 320

Actual - Traceback (most recent call last):

  File "args_and_kwargs.py", line 8, in <module>

    print(mul(nums))

NameError: name 'nums' is not defined

1 Answer

0 votes
by (25.1k points)

In python you ned to use a list for that. Just split the input with space as the delimiter and convert each elemnt from string to inteeger in a list comprehension. Like this:

nums = input("Enter the Numbers to be multiplied : ").split(" ")

nums = [int(num) for num in nums]

print(mul(*nums))

Browse Categories

...