w3resource

NumPy: Sum and compute the product of a NumPy array elements

NumPy: Array Object Exercise-99 with Solution

Write a NumPy program to sum and compute the product of a numpy array of elements.

Pictorial Presentation:

Python NumPy: Sum and compute the product of a numpy array elements

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing floating-point values
x = np.array([10, 20, 30], float)

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating the sum of the array elements will be displayed
print("Sum of the array elements:")

# Calculating and printing the sum of the elements in the array 'x' using 'sum()'
print(x.sum())

# Printing a message indicating the product of the array elements will be displayed
print("Product of the array elements:")

# Calculating and printing the product of the elements in the array 'x' using 'prod()'
print(x.prod()) 

Sample Output:

Original array:                                                                   
[ 10.  20.  30.]                                                                
Sum of the array elements:                                                          
60.0                                                                       
Product of the array elements:                                                      
6000.0 

Explanation:

In the above exercise –

‘x = np.array([10, 20, 30], float)’ creates a NumPy array 'x' with the elements 10, 20, and 30 of float data type.

print(x.sum()): Calculate the sum of all elements in the 'x' array using the 'sum()' method and print the result. In this case, the sum is 10 + 20 + 30 = 60.

print(x.prod()): Calculate the product of all elements in the 'x' array using the 'prod()' method and print the result. In this case, the product is 10 * 20 * 30 = 6000.

Python-Numpy Code Editor:

Previous: Write a NumPy program to convert the raw data in an array to a binary string and then create an array.
Next: Write a NumPy program to take values from a source array and put them at specified indices of another array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/numpy/python-numpy-exercise-99.php