To practice and better understand the for
loop, I have designed a function that computes the factorial of a given number. I get pretty much everything beside the role of the iterator (loop variable).
Here is the function I designed:
def main():
print("This program computes the factorial of a number!")
n = eval(input("Enter a whole number: "))
fact = 1
for factor in range(n, 1, -1):
fact = fact * factor
print("The factorial of {} is {}!".format(n, fact))
main()
When I run the program for the factorial of 6, the function prints:
The factorial of
6
is 720!
I'm looking to understand what role and relationship the input n
given by the program user has on the iterator (loop variable) factor
?
To test this out, I removed the iterator (loop variable) factor
and replaced it with the input variable n
.
def main():
print("This program computes the factorial of a number!")
n = eval(input("Enter a whole number: "))
fact = 1
for n in range(n, 1, -1):
fact = fact * n
print("The factorial of {} is {}!".format(n, fact))
main()
When I run the program for the same factorial of 6
that I used with the previous piece of code, the function prints:
The factorial of
2
is 720!
Why do I get two different answers when I ask Python to compute the same factorial number. Clearly, there is something not right with the latter piece of code, which I assume has something to do with the relationship between the input variable n
and the iterator (loop variable) factor
.
n
by using it as a loop variable in the second version.eval
.int(input(...))
is enough.input()
was scrapped.