Skip to Main Content
Blog

Calculate Alternating Integer Series in Python

Calculate Alternating Integer 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: 1 - 2 + 3 - ... ± n.
	"""

	total = 0
	sign = +1

	for i in range(1, n + 1):
		total += sign * i
		sign *= -1

	return total


if __name__ == "__main__":
	main()