Python Forum

Full Version: factorial, repeating
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
1.n = int(input())
2.
3.factorial = 1
4.while n > 1:
5.
6. factorial *= n
7. n -= 1
8.
9.print(factorial)
10.
11.#I would like to write a code where I could repeat the action endlessly and ask the user for the number he wants to find the factorial. I've tried both "break" and "continue", just in the book I'm reading a summary of "while". I also wanted to write "input", but the code did not work
You can repeat endlessly with a while True loop
while True: # code to be repeated endlessly
I dont get the question completely but i gues this would help
def iter_factorial(n): factorial=1 n = input("Enter a number: ") factorial = 1 if int(n) >= 1: for i in range (1,int(n)+1): factorial = factorial * i return factorial num=int(input("Enter the number: ")) print("factorial of ",num," (iterative): ",end="") print(iter_factorial(num))
If this does not help, try to go through this article factorial in python
I believe all is asked for is wrapping a loop around the loop. To elaborate slightly on Gribouillis:
while True: try: n = int(input('Enter number or done: ')) except ValueError: break # Quit if input is not a number factorial = 1 for i in range(1, n+1): factorial *= i print(f'{n}! = {factorial}')
I hate to spoil the party:
import math print(math.factorial(3))
Paul