""" # This file is unit01_loop_structure.py. It contains a sample loop that # calculates the sum of the squares of the numbers 1 through 10. # George Gollin, University of Illinois, January 15, 2017 """ # initialize variables here. take note of the names. # the "accumulator variable" is where we sum the effects of whatever we # calculated during successive passes through the loop. we initialize it to # zero. I am using the decimal point to make it a floating point variable, # which isn't really necessary. accumulator = 0.0 # the "increment variable" is something we'll generally need to calculate each # pass through the loop. after we calculate it we will add it to the accumulator # variable. Since it will vary each time we go through the loop we don't need # to initialize it here. # specify the lower and upper limits for the loop now. Use the range function, # which takes two integers as arguments, and creates a sequence of unity-spaced # numbers. Note that the upper limit is not included in the sequence: # range(1,5) gives the numbers 1, 2, 3, 4. Note that I will add 1 to the upper # limit in my range function since range will stop short of this by 1. lower_limit = 1 upper_limit = 10 # here's the loop. note the "whitespace" that is required, as well as the end- # of line colon. for index in range(lower_limit, upper_limit + 1): # in python we square things using a double asterisk followed by the # desired power. Note that a carat will not work: 3^2 is NOT 9. increment = index ** 2 # now add into the accumulator. accumulator = accumulator + increment # I could have written all of this much more compactly using the += # operator, but that'd be confusing, and you might find that it makes for # buggy, unclear code. # we end the loop by having a line of unindented code. print("all done! sum of squares is ", accumulator) ################################################################### """ Note that I could have written the code more compactly in a single line, but it would have been harder to decipher: >> print(sum(np.array(range(1,11))**2)) 385 """