Sum of Harmonic Series
Add harmonic-series terms and format the total to four decimal places. Students trace Python true division, a floating-point accumulator, and display rounding.
1# Take n2n = int(input("Enter n: "))34# Calculate sum5harmonic_sum = 06for i in range(1, n + 1):7 harmonic_sum += 1 / i89print(f"Sum: {harmonic_sum:.4f}")
Output
Enter n: 5 Sum: 2.2833
In this one
- Evaluate reciprocals
- Accumulate floats
- Format four decimal places
How it works
- 1
Initialize harmonic_sum to zero.
- 2
Add 1 / i for denominators one through n.
- 3
Print the completed total with .4f formatting.
Edge cases
Why not use //?
Why not use //?
Floor division would turn later positive fractions into zero.
What if n is zero?
What if n is zero?
No division runs and the displayed total is 0.0000.
What's going on
The loop calculates 1 / i for denominators one through n. Unlike printing fraction labels, / evaluates each term numerically.
The accumulated value is formatted with .4f at the end. For two terms the sum is 1.5, displayed as 1.5000. Formatting changes the printed representation, not the stored value; floating-point addition is still approximate.
Why not use //? Floor division would turn later positive fractions into zero.
What if n is zero? No division runs and the displayed total is 0.0000.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does .4f control?
Pick an answer to check it.
Question 2
Why not use //?
Pick an answer to check it.
Questions people ask
Why not use //?
Floor division would turn later positive fractions into zero.
What if n is zero?
No division runs and the displayed total is 0.0000.
What does .4f control?
Four digits after the decimal point.
๐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