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

Harmonic Series Sum

Calculate a numeric harmonic sum with floating-point division. Students add reciprocals to a float total rather than printing the symbolic fraction expression.

IntermediatePhase 6 - Category 4: Mathematical CombinationsExample 4 of 10
harmonic-series-sum.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate harmonic sum
5total = 0.0
6for i in range(1, n + 1):
7 total += 1.0 / i
8
9print(f"Harmonic sum: {total}")

Output

Enter n: 5
Harmonic sum: 2.283333333333333

In this one

  • Evaluate rather than format fractions
  • Use float division
  • Keep denominator zero excluded

How it works

  1. 1

    Initialize total as 0.0.

  2. 2

    Add 1.0 / i for i beginning at one.

  3. 3

    Print the evaluated harmonic total.

Edge cases

Why begin the denominator at one?

Why begin the denominator at one?

Division by zero is undefined and would raise an error.

What happens for n = 0?

What happens for n = 0?

The empty loop leaves total at 0.0.

What's going on

This harmonic lesson evaluates the fractions and adds them. total starts as 0.0, and each term uses 1.0 / i.

For three terms, the stored total approximates 1 + 1/2 + 1/3. The final f-string displays Python's usual float representation without a .4f limit. Unlike Print Harmonic Series, this program produces one numeric result, not plus-separated fraction labels.

Why begin the denominator at one? Division by zero is undefined and would raise an error.

What happens for n = 0? The empty loop leaves total at 0.0.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Does the code print 1/1 + 1/2 text?

Pick an answer to check it.

Question 2

Why begin the denominator at one?

Pick an answer to check it.

Questions people ask

Why begin the denominator at one?

Division by zero is undefined and would raise an error.

What happens for n = 0?

The empty loop leaves total at 0.0.

Does the code print 1/1 + 1/2 text?

No, it prints the evaluated sum.