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

Print Harmonic Series

Print a symbolic harmonic series without adding it. Students build fraction labels with Python f-strings and place plus signs only between the displayed terms.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 11 of 13
print-harmonic-series.py
1# Take n
2n = int(input("Enter n: "))
3
4# Print harmonic series
5print("Harmonic series:")
6for i in range(1, n + 1):
7 print(f"1/{i}", end="")
8 if i < n:
9 print(" + ", end="")
10print()

Output

Enter n: 5
Harmonic series:
1/1 + 1/2 + 1/3 + 1/4 + 1/5

In this one

  • Format symbolic fractions
  • Place separators between terms
  • Distinguish text from evaluation

How it works

  1. 1

    Visit denominators one through n.

  2. 2

    Print each fraction label without evaluating it.

  3. 3

    Add plus only before another term remains.

Edge cases

Does this calculate decimal fractions?

Does this calculate decimal fractions?

No. The fractions are strings in an f-string.

What if n is one?

What if n is one?

It prints 1/1 with no plus sign.

What's going on

This lesson prints the text 1/1 + 1/2 and so on; it does not evaluate a harmonic sum. i supplies each denominator from one through n.

The separator prints only when i < n, avoiding an extra plus sign after the last fraction. end keeps the whole expression on one line. Distinguish this formatting task from the numeric harmonic-sum lessons, which use division and an accumulator.

Does this calculate decimal fractions? No. The fractions are strings in an f-string.

What if n is one? It prints 1/1 with no plus sign.

Quiz

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

Question 1

Why check i < n?

Pick an answer to check it.

Question 2

Does this calculate decimal fractions?

Pick an answer to check it.

Questions people ask

Does this calculate decimal fractions?

No. The fractions are strings in an f-string.

What if n is one?

It prints 1/1 with no plus sign.

Why check i < n?

To avoid a trailing plus separator.