#WSQ06 – Fatorial calculator

Here are the instructions:

Create a program that asks the user for a non-negative integer (let’s call that number n) and display for them the value of n! (n factorial).After showing them the answer, ask them if they would like to try another number (with a simple y/n response) and either ask again (for y) or quit the program and wish them a nice day (if they answered n). For the Python group, resist the urge to call math.factorial(n). Yes that would solve the problem but what would we do if there was no math.factorial() and we had no internet to find someone’s solution? There are two basic approaches: a loop with an accumulator of the multiplication and a recursive solution. Choose one and implement that. Once that is done, try the other way. If you used a while loop for the solution with a loop, try structuring this with a for loop (or vice-versa).

 

  1. I defined the function factorial(n), with the parameter n. I set product=1 in the second line as an initial value.
  2. The for loop helps us to write programs that implement iteration. In other words, the for do something for each of the integers in the range n.
  3. *= is an accumulator, which basically comes to writing product = product * (1+i)
  4. Once again, in line 8, answer=”YES” is only an initial value telling the program to keep running. Indeed, if the answer was “NO”, the program would terminate itself.
  5. The while loop tells the shell to keep asking if the user wants to know any factorial until the later says no, then the program closes.

 

I found some useful informations on the following sites:

http://www.ics.uci.edu/~xhx/courses/python/tmp/Lecture3.ppt

http://stackoverflow.com/questions/17953940/yes-or-no-output-python

 

 

Leave a comment