Calculate Alternating Factorial Series in Python
def main():
"""
Prints the sum of a series.
"""
n = int(input("Enter n: "))
s = series(n)
print(s)
def series(n: int):
"""
Calculates the sum of the series: 0! - 1! + 2! - 3! + ... ± n.
"""
# Initialize the values with 0!
ith_factorial = 1
series_sum = 1
sign = -1
# Calculate the sum from 1!...n
for i in range(1, n + 1):
ith_factorial *= i
series_sum += sign * ith_factorial
sign *= -1
return series_sum
if __name__ == "__main__":
main()