Brief Introduction:
This Python code calculates the factorial of a given number using a for loop and displays the result.
Code:
#Function to calculate factorial
#The requirements are listed below:
#1. The function should accept one integer argument from user.
#2. Calculate factorial. For example:
#3. Display factorial
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)
num = int(input("Enter the number: "))
calcFact(num)
Logic:
- The code defines a function named ‘calcFact’ that accepts one integer argument ‘num’.
- It initializes a variable ‘fact’ to 1.
- Then, it runs a for loop starting from ‘num’ and decreasing by 1 each time.
- Inside the loop, it updates the ‘fact’ variable by multiplying it with the current iteration value.
- Finally, it prints the factorial of the input number by displaying the value of ‘num’ and ‘fact’.
Output:
The code prompts the user to enter a number, calculates the factorial of the input number using the ‘calcFact’ function, and displays the factorial as “Factorial of [num] is [fact]”.
Enter the number: 10
>> Factorial of 10 is 3628800