A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

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