Print Product of Numbers in List Using While Loop in Python

Now we going to write a program to find the product of all numbers in a user-defined list using a while loop.

This program uses a while loop to find the product of all the numbers in a list.

    Simple code:

    nums = [int(num) for num in input("Enter numbers separated by space: ").split()]
    i = 0
    product = 1
    
    while(i < len(nums)):
        product *= nums[i]
        i += 1
    
    print("The product of the numbers is", product)

    Output:

    Enter numbers separated by space: 4 2 8 6 3 4 7 5
    The product of the numbers is 161280

    Code with explanation:

    # Ask the user to enter a list of numbers separated by spaces and store them in a list called 'nums'
    nums = [int(num) for num in input("Enter numbers separated by space: ").split()]
    
    # Initialize an index variable 'i' to 0 and a product variable to 1
    i = 0
    product = 1
    
    # Use a while loop to iterate through all the numbers in the list and multiply them together
    while(i < len(nums)):
        # Multiply the current number to the product
        product *= nums[i]
        
        # Move to the next number in the list
        i += 1
    
    # Print the product of the numbers
    print("The product of the numbers is", product)

    Explanation:

    • This program prompts the user to enter a list of numbers separated by spaces using the input() function and stores them in a list called ‘nums’.
    • Two variables ‘i’ and ‘product’ are initialized to 0 and 1, respectively.
    • A while loop is used to iterate through all the numbers in the list and multiply them together. At each iteration, the current number is multiplied to the product and the loop moves to the next number in the list.
    • Finally, the program prints the product of the numbers using the print() function.
    Was this helpful?
    YesNo

    Related Articles:

    Recent Articles:

    0 0 votes
    Article Rating
    Subscribe
    Notify of
    0 Comments
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x