Exercise
Iterative Implementation Of The Factorial Function
Objective
Develop a Python program that calculates the factorial of a given number using an iterative (non-recursive) method. For instance, when running print(factorial(6)), the output will be 720.
Example Python Exercise
Show Python Code
# Function to calculate the factorial of a number using an iterative method
def factorial(n):
# Initialize result to 1 (the factorial of 0 is 1)
result = 1
# Loop through numbers from 1 to n and multiply them to calculate the factorial
for i in range(1, n + 1):
result *= i
# Return the calculated factorial
return result
# Main function to demonstrate the factorial function
def main():
# Input number
number = 6
# Call the factorial function and store the result
result = factorial(number)
# Print the result
print(f"The factorial of {number} is {result}")
# Run the main function
if __name__ == "__main__":
main()
Output
The factorial of 6 is 720
Share this Python Exercise