num = int(input("Enter a number to find its factorial: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is: {factorial}")
#source code --> clcoding.com
Code Explanation:
1. Taking Input from the User
num = int(input("Enter a number to find its factorial: "))
input(): Prompts the user to enter a number as a string.
int(): Converts the input string into an integer so it can be used in calculations.
The integer is stored in the variable num.
2. Initializing the Factorial Variable
factorial = 1
The factorial variable is initialized to 1 because multiplying by 1 does not affect the result.
This variable will be used to store the cumulative product of numbers from 1 to num.
3. Calculating the Factorial Using a Loop
for i in range(1, num + 1):
factorial *= i
range(1, num + 1): Generates a sequence of numbers from 1 to num (inclusive).
For example, if num = 5, the range will generate: [1, 2, 3, 4, 5].
Iterative Multiplication:
The loop runs once for each number in the range.
In each iteration, the value of factorial is updated by multiplying it with the current value of i.
4. Printing the Result
print(f"The factorial of {num} is: {factorial}")
The calculated factorial is displayed using an f-string, which allows embedding variables directly within the string.
0 Comments:
Post a Comment