Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 12 of 13
sum-of-harmonic-series.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate sum
5harmonic_sum = 0
6for i in range(1, n + 1):
7 harmonic_sum += 1 / i
8
9print(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. 1

    Initialize harmonic_sum to zero.

  2. 2

    Add 1 / i for denominators one through n.

  3. 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.