So I;m trying to write a function file(s:int, filn:str)
-> None that writes the value of n! to a file with the specified filename.
n! is n the number to the extent which the factorial will be calculated.
For example:
file(10, 'test.out')
# test.out
3628800
Here is my attempt at the code so far, which clearly doesn't work at all, what should I change?
filn = 100
def file(s:int, filn:str):
s = open(filn)
q = s.read()
for i in range(1,s 1):
return (q * i)
print(file(10, 'data'))
CodePudding user response:
Calculate factorial value and when write it into a file.
def file(x: int, file_name: str) -> None:
factorial = 1
for i in range(2, x 1):
factorial *= i
with open(file_name, 'w') as file:
file.write(str(factorial))
This function writes value of x!
into file with file_name
name.
CodePudding user response:
Unless you insist on calculating the factorial yourself, you should probably also use the math library for efficiency.
Using Ratery's answer with the math library:
from math import factorial
def file(x: int, file_name: str) -> None:
with open(file_name, 'w') as file:
file.write(str(factorial(x)))