Reputation: 27
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
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