'what is wrong with python my python code in *args?
can anyone can help me I was expected that the output is 625 but it shows the output is zero
def add(*args):
sum = 0
for i in args:
sum *= i
return sum
print(add(5, 5, 5, 5))
Solution 1:[1]
You are setting the sum variable to 0, an in the for loop you are multiplying the sum with i. Any number multiplied with 0 is 0.
Solution 2:[2]
>>> def multiply(*args):
... result = 1
... for i in args:
... result *= i
... return result
...
>>> print(multiply(5,5,5,5))
625
Or rather if you wanted to add
>>> def add(*args):
... result = 0
... for i in args:
... result += i
... return result
...
>>> print(add(5,5,5,5))
20
Or rather do this pythonic way
>>> mul = lambda x,y: x*y
>>> functools.reduce(mul, [5,5,5,5])
625
Or rather single liner
>>> functools.reduce(lambda x,y : x*y, [5,5,5,5])
625
>>> functools.reduce(lambda x,y : x+y, [5,5,5,5])
20
- Please define your function to have meaningful names.
- Don't use inbuilt names like "sum"
- Have meaningful variable names
Solution 3:[3]
First of all, anything multiplied by zero is zero. Therefore if you want to multiply the numbers received, you need to change sum = 0 to sum = 1.
Secondly, don't use sum as a variable or function name, as it is a built-in function in python. It is also misleading as you want your function to multiply the given args (and therefore also don't call the function add). To achieve a readable code, you should have meaningful variable and function names.
Also, your first line isn't indented correctly. You can read about python indentation here.
Putting it all together:
def multiply(*args):
multiplication = 1
for i in args:
multiplication *= i
return multiplication
print(multiply(5, 5, 5, 5))
Output:
625
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TheCoder1001 |
| Solution 2 | |
| Solution 3 |
