I'm just learning through edX's course and they'd like me to write a for loop to find 5 factorial and only printing 120/the final product and not the whole list.
I've tried this:
mystery_int = 5
for answer in range(1,5):
mystery_int *= answer
print(mystery_int)
I'd like the result to be just "120" but the actual output is the whole list
5
10
30
120
mystery_int = 10 # change this value to calculate new factorial
factorial = 1
for num in range(2, mystery_int + 1):
factorial *= num
print('{:,}'.format(factorial))
As pointed out in a comment you need to move the print()
statement outside of the for loop scope and it will print only the result after the loop ends. Also, adding a comma in the { } with format adds a thousands separator.
I assume you are not using function to calculate the factorial. Here is what you can do, as suggested in comments:
mystery_int = 5
# you can skip an extra iteration of multiplying by 1
for answer in range(2,5):
mystery_int *= answer
print(mystery_int)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.