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 rep eat 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
=
n
∑
k=1
1
k
Type it in and run it a few times to get a feeling ...
Get A Concise Introduction to Programming in Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.