Write a Python Program Calculate The Product Multiplying All The Numbers of a Given Tuple

Hi, in this article lets learn how to Calculate all the numbers of a given tuple using Python Programming Language. Tuple is immutable that means once initialized we cannot change the items present in Tuple.

Tuple is a data structure containing multiple data types having separated by comma enclosed with round braces.

 

product of tuple

 

 

Write a Python Program Calculate The Product, Multiplying All The Numbers of a Given Tuple.

Lets take a tuple variable and initialize it to random values of integers. Then take another variable product and keep multiplying with all the items of tuple by traversing it using for loop. Finally print the product using print() function.

my_tuple = (12, 34, 67, 89)

product = 1
for item in my_tuple:
    product = product * item

print("Product of tuple is :", product)

 

OUTPUT : 

 

Write a Python Program Calculate The Product, Multiplying All The Numbers of a Given Nested Tuple

If nested tuple is the input variable then to find the product of all the items in the tuple, use recursion. Define a product global variable outside the function and use it in the function. Use for loop to check if data is integer - if integer multiply it with product, if tuple call the function with input argument as item. Use instance() function to check if item is integer / tuple.


Below is the program to find product of nested tuple

nested_tuple = (2, 3, 4, 5, (6, 7), (1, 1, (1, 1, (1, 1, 1))))

product = 1


def find_product(data):

    global product

    for item in data:
        if isinstance(item, int):
            product = product * item
        elif isinstance(item, tuple):
            find_product(item)


find_product(nested_tuple)
print("Product of tuple is :", product) 

 

OUTPUT :

Product of tuple is : 5040

Conclusion : hope you understood the program completely, if any queries comment down below.

Post a Comment

0 Comments