Help me in solving PYTH101 problem

My issue

My code

# Solution as follows

n = int(input())

i = 1
factorial = 1

while i <= n:
    # We need to multiply by i in each iteration
    factorial = i * factorial
    i = i + 1
print("The factorial of the given number is:", factorial)

Learning course: Learn Python
Problem Link: CodeChef: Practical coding for everyone

I need a detailed explanation please.

This Python code calculates the factorial of a given input number ‘n’ using a while loop. Let’s go through it step-by-step:

  1. n = int(input()): This line of code prompts the user to enter an integer value, and it stores that value in the variable ‘n’. The ‘int()’ function is used to convert the user input, which is initially a string, into an integer data type.
  2. i = 1: This line initializes a variable ‘i’ to 1. This variable will be used as a counter to iterate through the loop.
  3. factorial = 1: This line initializes the variable ‘factorial’ to 1. This variable will be used to store the factorial value and will be updated inside the loop.
  4. while i <= n:: This line starts a while loop that will execute the block of code below it as long as the condition ‘i <= n’ is true. The loop will run until the value of ‘i’ becomes greater than ‘n’.
  5. factorial = i * factorial: Inside the loop, this line updates the ‘factorial’ variable by multiplying its current value with the value of ‘i’. During the first iteration (when i = 1), this line sets the factorial to 1 * 1, which is still 1. In the subsequent iterations, it multiplies the previous factorial with the next ‘i’, effectively calculating the factorial of ‘i’ so far.
  6. i = i + 1: Inside the loop, this line increments the value of ‘i’ by 1 in each iteration. It ensures that the loop proceeds to the next number until it reaches ‘n’.
  7. After the loop finishes, it means ‘i’ has become greater than ‘n’, and the code execution continues to the next line.
  8. print("The factorial of the given number is:", factorial): This line prints the calculated factorial value, which is stored in the variable ‘factorial’. It displays the result in the format “The factorial of the given number is: X”.

The program calculates the factorial of the input number ‘n’ by iterating through each number from 1 to ‘n’ and multiplying them together. The final result is displayed at the end of the program.