#! /usr/bin/env python3 # def python05 ( ): import matplotlib.pyplot as plt import numpy as np print ( '' ) print ( 'python05():' ) print ( ' Exercises for loops.' ) # # Loop to evaluate the triangular numbers. # print ( '' ) print ( ' Evaluate triangular numbers for 0 <= n < 11.') print ( '' ) for n in range ( 0, 11 ): print ( ' t(', n, ') = ', n * ( n + 1 ) / 2 ) print ( '' ) print ( ' Repeat calculation, using // for integer division.') print ( '' ) for n in range ( 0, 11 ): print ( ' t(', n, ') = ', n * ( n + 1 ) // 2 ) # # Code which includes nonindented statements before and after loop. # print ( '' ) print ( ' Non-indented statements before and after loop.') print ( '' ) s = 0 print ( ' S starts out at ', s ) for n in range ( 1, 11 ): t = n * ( n + 1 ) // 2 s = s + t print ( ' t(', n, ') = ', t ) print ( ' Sum of triangular numbers is ', s ) # # The range statement returns a list of loop indices. # print ( '' ) print ( ' The range statement returns a list of loop indices.') print ( '' ) r0 = list ( range ( 10 ) ) print ( ' range ( 10 ) = ', r0 ) r1 = list ( range ( 0, 10 ) ) print ( ' range ( 0, 10 ) = ', r1 ) r2 = list ( range ( 10, 10 ) ) # Oops print ( ' range ( 10, 10 ) = ', r2 ) r3 = list ( range ( 10, 0 ) ) # Oops print ( ' range ( 10, 0 ) = ', r3 ) r4 = list ( range ( 10, 0, -1 ) ) print ( ' range ( 10, 0, -1 ) = ', r4 ) r5 = list ( range ( 0, 10, 2 ) ) print ( ' range ( 0, 10, 2 ) = ', r5 ) # # Using a list instead of range(): # print ( '' ) print ( ' We can use a list instead of range().' ) print ( '' ) UScoins = [ 1, 5, 10, 25, 50, 100 ] print ( ' UScoins = ', UScoins ) sum = 0 for coin in UScoins: sum = sum + coin print ( ' The sum of a collection of US coins is ', sum ) print ( '' ) friends = [ 'Alice', 'Bob', 'Carol', 'David' ] print ( ' friends = ', friends ) for friend in friends: print ( ' My friend', friend, 'has a name of length ', len ( friend ) ) print ( '' ) patient0 = [ 'Robert Baratheon', 235.4, 73, False ] print ( ' patient0 = ', patient0 ) patient1 = [ 'Arya Stark', 134.7, 68, True ] print ( ' patient1 = ', patient1 ) patients = [ patient0, patient1 ] print ( ' patients = ', patients ) for name, weight, height, vax in patients: print ( name, ' weighs ', weight, 'lbs and is ', height, 'inches tall.' ) # # Nested loop. # print ( '' ) print ( ' A nested loop allows us to process matrix entries.' ) print ( '' ) m = 4 n = 3 A = np.random.rand ( m, n ) print ( ' A = ', A ) average = 0.0 for i in range ( 0, m ): for j in range ( 0, n ): average = average + A[i,j] average = average / m / n print ( '' ) print ( ' average matrix entry is ', average ) # # While loop for triangular numbers. # print ( '' ) print ( ' While loop for triangular numbers.' ) print ( '' ) n = 1 while ( n * ( n + 1 ) // 2 < 1000 ): n = n + 1 print ( ' 1000 <= t(', n,') = ', n * ( n + 1 ) // 2 ) return if ( __name__ == "__main__" ): python05 ( )