def factorial(n):
result = 1 # Initialize the factorial result to 1
i = 1 # Start counter at 1
while i <= n: # Loop through numbers from 1 to n
result *= i # Multiply result by the current counter i
i += 1 # Increment the counter
return result # Return the computed factorial
# Loop through numbers 1 to 10
num = 1 # Start counter at 1
while num <= 10: # Loop until num reaches 10
print(f"Factorial of {num} is {factorial(num)}") # Print the factorial
num += 1 # Increment counter
1 Like
Answer by CoPilot AI:
Factorial Function
- Function Definition:
def factorial(n):
defines a function namedfactorial
that takes one parametern
. - Initialization:
result = 1
initializes the variableresult
to 1, which will hold the final factorial value. - Loop:
while i <= n:
starts a loop that runs from 1 ton
. - Multiplication:
result *= i
multipliesresult
by the current value ofi
. - Increment:
i += 1
incrementsi
by 1. - Return:
return result
returns the computed factorial value.
Loop to Print Factorials
- Initialization:
num = 1
initializes the variablenum
to 1. - Loop:
while num <= 10:
starts a loop that runs from 1 to 10. - Print:
print(f"Factorial of {num} is {factorial(num)}")
prints the factorial ofnum
by calling thefactorial
function. - Increment:
num += 1
incrementsnum
by 1.
Summary
- The
factorial
function calculates the factorial of a given numbern
. - The second part of the code prints the factorials of numbers from 1 to 10.
Documentation
https://docs.python.org/3/
scikit-learn.org
I use YouTube when I get stuck and so try to find a tutorial channel that you enjoy learning from.
1 Like