Q:

Write a python program to use the loop to find the factorial of a given number.

belongs to collection: Python Loop Exercises

0

Find the factorial of a given number

Write a program to use the loop to find the factorial of a given number.

The factorial (symbol: !) means to multiply all whole numbers from the chosen number down to 1.

For example: calculate the factorial of 5

5! = 5 × 4 × 3 × 2 × 1 = 120

Expected output:

120

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • Set variable factorial =1 to store factorial of a given number
  • Iterate numbers starting from 1 to the given number n using for loop and range() function. (here, the loop will run five times because n is 5)
  • In each iteration, multiply factorial by the current number and assign it again to a factorial variable (factorial = factorial *i)
  • After the loop completes, print factorial

Solution:

num = 5
factorial = 1
if num < 0:
    print("Factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    # run loop 5 times
    for i in range(1, num + 1):
        # multiply factorial by current number
        factorial = factorial * i
    print("The factorial of", num, "is", factorial)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Reverse a given integer number using python progra... >>
<< Display Fibonacci series up to 10 terms using pyth...