# -*- coding: utf-8 -*- """ Created on Wed Sep 30 11:07:55 2020 @author: jbobowsk """ # This tutorial will introduce simple implementations of for loops. # Here's the simplest for loop. for i in range(10): print(i) # Note that the loop starts from i = 0 and has 10 iterations. Therefore, # the output is i = 1, 2, 3, ..., 9. Also, Python will loop over only the lines # following the 'for' statement that are indented. Note the difference in the # outputs from the following two blocks of code. # i**2 is in the loop: print('i**2 is in the loop:') for i in range(10): print(i) print(i**2) # i**2 is NOT in the loop: print('\ni**2 is NOT in the loop:') for i in range(10): print(i) print(i**2) # The loop can be made to increment in steps of two as follows: import numpy as np print('\nStep by two:') for i in np.arange(0, 10, 2): print(i) # Often, you may wish to perform calculations within a loop and then store # the results of those calculations in a list. # The first step is to create a list of x values that we will iterate over x = np.arange(0, 1.9, 0.1) print('x:', x) # Next, we will create an empty list that we will use to store the results # of out calculation. results = [] # We can now use our results list within a for loop and append values # to list as the loop iterates. umax = 0.54 M = -4.2703 D = 1.8 for i in x: results = results + [(umax/M)*np.log(1 + (np.exp(M)-1)*(i/D)*np.exp(1 - i/D))] print('Results:',results) # In fact, we can now easiy plot results vs x. import matplotlib.pyplot as plt plt.plot(x, results, 'bo') plt.xlabel('x'); plt.ylabel('results'); plt.axis((0, 1.8, 0, 0.6))