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 of6is 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 of2is 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.
Start with your working code:
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()
Add a print (protip: this is a highly useful debugging trick):
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):
print(factor) # Add this line
fact = fact * factor
print("The factorial of {} is {}!".format(n, fact))
main()
You should see output like this:
6
5
4
3
2
The factorial of 6 is 720!
As you can see, the factor variable changes each time through the loop. It takes on each successive value in the range() you specified.
When you change the loop variable to n, it's getting overwritten with these values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With