Python Exercise: Multiply all the numbers in a list
Python Functions: Exercise-3 with Solution
Write a Python function to multiply all the numbers in a list.
Sample Solution:
Python Code:
# Define a function named 'multiply' that takes a list of numbers as input
def multiply(numbers):
# Initialize a variable 'total' to store the multiplication result, starting at 1
total = 1
# Iterate through each element 'x' in the 'numbers' list
for x in numbers:
# Multiply the current element 'x' with the 'total'
total *= x
# Return the final multiplication result stored in the 'total' variable
return total
# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)
print(multiply((8, 2, 3, -1, 7)))
Sample Output:
-336
Explanation:
In the exercise above the code defines a function named "multiply()" that takes a list of numbers as input and returns the product of all the numbers in the list. The final print statement demonstrates the result of calling the "multiply()" function with a tuple containing the numbers (8, 2, 3, -1, 7).
Pictorial presentation:
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python function to sum all the numbers in a list.
Next: Write a Python program to reverse a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/python-functions-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics