3
Loops and Branching
3.1 The for Loop
Many computations are repetitive by nature and programming languages have
certain loop structures to deal with this. One such loop structure is the for loop.
3.1.1 Example: Printing the 5 Times Table
Assume the task is to print out the 5 times table. Before having learned about loop
structures in programming, most of us would first think of coding this like:
# Naively printing the 5 times table
print(’{:d}*5 = {:d}’.format(1, 1*5))
print(’{:d}*5 = {:d}’.format(2, 2*5))
print(’{:d}*5 = {:d}’.format(3, 3*5))
print(’{:d}*5 = {:d}’.format(4, 4*5))
print(’{:d}*5 = {:d}’.format(5, 5*5))
print(’{:d}*5 = {:d}’.format(6, 6*5))
print(’{:d}*5 = {:d}’.format(7, 7*5))
print(’{:d}*5 = {:d}’.format(8, 8*5))
print(’{:d}*5 = {:d}’.format(9, 9*5))
print(’{:d}*5 = {:d}’.format(10, 10*5))
© The Author(s) 2020
S. Linge, H. P. Langtangen, Programming for Computations - Python,
Texts in Computational Science and Engineering 15,
https://doi.org/10.1007/978-3-030-16877-3_3
59
Précédent

- 81/350

Suivant