O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4

Repetition: For Loops

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+ 1 2 + 1 3 + 1 4 ++ 1 n = k=1 n 1 k

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required