Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to multiply all the numbers in a sequence (python)

Like if i told the program n=10, how would I make it return 10*9*8*7*6*5....1?

I thought a while loop but I feel I messed up somewhere because it doesn't sum up all of the numbers in the sequence.

My current code looks like this

def product(n):
  i=n
  a=n-1
  while a>0:
    return i * a
    b=i * a
    a=a-1
    i=i-1

Are there any better ways to do it without using recursion? Sorry for the incredibly beginner question, but I'm trying to teach myself how to code. You gotta start somewhere!

Thanks!

like image 921
Billy Thompson Avatar asked Dec 04 '22 02:12

Billy Thompson


1 Answers

Since you are trying to learn to code, I won't give you a total solution, but I'll give you a few hints instead:

  • Have a for loop that runs up from 1 to n (using range(1, n+1)) instead of your while-loop. This will generate the values that you want to multiply and iterate the right number of times (which can be a bit tricky with while loops sometimes).

  • Have a variable named product to store the result of the multiplications each time through the loop.

  • Initialize product before you enter the for-loop. Once inside you'll be just updating the value of product.

  • After you are done with the loop, you can use the return statement to return the value of product.

  • Finally, for testing purposes, you may want to start out with a small value of n, like 4, and print out the values you are computing inside the loop to verify how your code is working.

There are more terse and pythonic ways to do this, but this uses the code structure you have already set up. And of course recursively as well as you mention too.

Once you master the basics, you'll appreciate the more idiomatic ways of writing this, or calling the appropriate functions that do this for you.

like image 181
Levon Avatar answered Dec 21 '22 22:12

Levon