Alternating Series Sum
Sum alternating reciprocal terms with conditions. Students trace odd-position addition, even-position subtraction, and a four-decimal display of the result.
1# Take n2n = int(input("Enter n: "))34# Calculate sum5sum_alt = 06for i in range(1, n + 1):7 if i % 2 == 1:8 sum_alt += 1 / i9 else:10 sum_alt -= 1 / i1112print(f"Sum: {sum_alt:.4f}")
Output
Enter n: 5 Sum: 0.7833
In this one
- Alternate fraction signs
- Test denominator parity
- Separate formatting from storage
How it works
- 1
Visit denominators one through n.
- 2
Add odd reciprocals and subtract even reciprocals.
- 3
Display the final total to four decimal places.
Edge cases
Which sign does the third term use?
Which sign does the third term use?
Plus, because three is odd.
What happens for n <= 0?
What happens for n <= 0?
The loop is empty and the total stays zero.
What's going on
The first reciprocal is added, the second subtracted, and the pattern repeats. The parity test uses the denominator i to choose the sign.
For two terms the result is 1 - 1/2 = 0.5. Each term uses / so fractions remain nonzero. The final .4f formats the total for display; it does not make the underlying arithmetic exact.
Which sign does the third term use? Plus, because three is odd.
What happens for n <= 0? The loop is empty and the total stays zero.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How is the second term handled?
Pick an answer to check it.
Question 2
Which sign does the third term use?
Pick an answer to check it.
Questions people ask
Which sign does the third term use?
Plus, because three is odd.
What happens for n <= 0?
The loop is empty and the total stays zero.
How is the second term handled?
Subtract 1 / 2.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum