Chapter 4

To this point, our Python programs have been limited to tasks that could be accomplished by a calculator. Repetition, the ability to repeat any section of a program, adds a surprising amount of new power.

Listing 4.1: Harmonic Sum

` 1 # harmonic.py`

2

` 3 def harmonic(n):`

` 4 # Compute the sum of 1/k for k=1 to n.`

` 5 total = 0`

` 6 for k in range(1, n + 1):`

` 7 total += 1 / k`

` 8 return total`

9

`10 def main():`

`11 n = int(input(’Enter a positive integer: ’))`

`12 print("The sum of 1/k for k = 1 to", n, "is", harmonic(n))`

13

`14 main()`

This program computes the harmonic sum

$1+\frac{1}{2}+\frac{1}{3}+\frac{1}{4}+\cdots +\frac{1}{n}={\displaystyle \sum _{k=1}^{n}\frac{1}{k}}$

Type it in and run it a few times to get a feeling for what it does and how it works. Try ...

Start Free Trial

No credit card required