Shivam Thaman
Shivam Thaman

Reputation: 27

How to accept the arguments from the user when using variable length Arguments in Python?

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

Upvotes: 0

Views: 247

Answers (1)

Wura
Wura

Reputation: 167

You can just use a list for that

def mul(*nums):
    result = 1
    for n in nums:
        result *= n
    return result 

nums = input("Enter the Numbers to be multiplied : ").split(" ")
nums = [int(num) for num in nums]
print(mul(*nums))

Upvotes: 1

Related Questions