Exercise 9

Write a program in Python that asks the user to enter an integer n and display its factorial n!


n = int(input("Enter an integer: "))
factorial = 1

for i in range(1, n+1):
    factorial *= i

print(f"The factorial of {n} is: {factorial}")


  1. The input() function: is used to get user input from the console.
  2. The int() function: is used to convert the user input (which is initially a string) to an integer.
  3. We initialize a variable factorial to 1: since the factorial of 0 is 1.
  4. We then use a for loop: to iterate from 1 to n, and multiply the factorial variable by each integer in this range.
  5. Finally, we use the print(): function to display the result of the factorial calculation.


The above code assumes that the user enters a positive integer. If you want to handle negative or non-integer inputs, you may need to add additional error-checking code.


Younes Derfoufi

One thought on “Solution Exercise 9: algorithm python that compute the factorial of an integer”

Leave a Reply