Home > Net >  How do you Multiply numbers in a loop in Python from a list of user inputs
How do you Multiply numbers in a loop in Python from a list of user inputs

Time:05-13

I need to create something that can multiply values no matter how many values there are. My idea is to use a list and then get the sum of the list with the sum function or get the first value of the list and set it as the total and then multiply the rest of the list by that total. Does anyone have a way to do it?

Here was my original idea:

total = 0.0
while True:
  number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1:  "))
  if number == 1:
    print(f"The total is: {sum(number)}")
    break
  else:
    total *= number

however as you may have guessed it just automatically multiplies it to 0 which equals zero. I would also like the code to work for subtraction and division (Already got Addition working)

thanks!

Thanks to the comments I worked out that the way to do it is by changing the beginning total to a 1 also I sent the wrong version of the code sorry the actual code when fixed is this:

total = 1 while True: number = int(input("Enter a number and I’ll keep multiplying until you enter the number 1: ")) if number == 1: break else: total *= number print(f"The total is: {total}")

I still can't work out to do the fancy code blocks I looked it up and it unfortunately did not work

CodePudding user response:

Since you are multiplying, you must start with 1 cause anything multiplied by 0 is 0. And idk why you need sum()

total = 1
while True:
  number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1:  "))
  if number == 1:
    print(f"The total is: {total}")
    break
  else:
    total *= number
  • Related