<jupyter_start><jupyter_text>Learn Python Loops**April 2021**Instruction, media content, examples and links to resources that will help you build a foundation for Python competency. Jupyter Notebooks are available on [Google Colab](https://colab.research.google.com/drive/1db7P4l-qfOMvpluQPYtdHDSqm4kDi3YB?usp=sharing) and [Github](https://github.com/AlphaWaveData/Jupyter-Notebooks/blob/master/Learn%20Python%20Loops.ipynb).Web Resources Docs.python.org - Control Flow Docs.python.org - Looping Techniques What are Python Loops?In the real world, you often need to repeat something over and over. It can be repetitive. When programming, though, if you need to do something 100 times, you certainly don't need to write it out in 100 identical lines of code. In Python, loops allow you to iterate over a sequence, whether that's a list, tuple, string, or dictionary. What types of Python Loops are there?There is a for loop and a while loop. We'll also go through list comprehensions, as a "Pythonic" powerful shortcut for operating on all the members of a list in a single line of code. The for statementA "for" loop in Python allows you to go through each item in a sequence, one at a time. This allows you to "iterate" through an "iterable", such as a Python list, and perform operations on each item one at a time.The simplest example is to step through the items in a list:<jupyter_code># In the below example, the for loop will step through each item in my_list, assign the element to a local variable ("x"), 
# and execute the block of code below it to print out x

my_list = [10, 20, 30, 40, 50, 60]

for x in my_list: #<--- x is a variable, who's scope is limited to the for loop. x can be named anything you'd like
    print(x)<jupyter_output>10
20
30
40
50
60<jupyter_text>The range() functionIn most cases, we will want to loop through a predetermined list. However, we can also generate a list to loop over "on the fly" with the range() function.<jupyter_code>for i in range(8):
    print(i)<jupyter_output>0
1
2
3
4
5
6
7<jupyter_text>You can use the range() function together with the len() function to loop through a list, along with a variable that has the current index in the sequence.<jupyter_code>my_list = [10, 20, 30, 40, 50, 60]

for i in range(len(my_list)):
    print(i, my_list[i])<jupyter_output>0 10
1 20
2 30
3 40
4 50
5 60<jupyter_text>EnumerateYou can achieve the same effect as above by using the enumerate() function, to get two values each step through the loop.<jupyter_code># the enumerate function will return two values each time the loop statement is run:
# "indx" will be the current index value, and "val" will be the current element of my_list
for indx, val in enumerate(my_list):
    print(indx, val)<jupyter_output>0 10
1 20
2 30
3 40
4 50
5 60<jupyter_text>Loop through the characters in a stringYou can also loop through all characters in a string of text in order.<jupyter_code>s = "One at a time"
for character in s:
    print(character)<jupyter_output>O
n
e
 
a
t
 
a
 
t
i
m
e<jupyter_text>Looping through a dictionary keys()You can step through the keys of a dictionary.<jupyter_code>my_dict = {'AAPL': 100, 'MSFT': 200, 'GOOG': 300, 'CSCO': 400}

for key in my_dict.keys():
    print(key)<jupyter_output>AAPL
MSFT
GOOG
CSCO<jupyter_text>items()Alternatively, you can step through all the items in the dictionary. Each item is a key-value pair.<jupyter_code>my_dict = {'AAPL': 100, 'MSFT': 200, 'GOOG': 300, 'CSCO': 400}

for key, value in my_dict.items():
    print('Key= ' + key + ', Value= ' + str(value))<jupyter_output>Key= AAPL, Value= 100
Key= MSFT, Value= 200
Key= GOOG, Value= 300
Key= CSCO, Value= 400<jupyter_text>The while loopThough not used as frequently as the for loop, the while loop allows you to execute a block of code until a certain condition is met. If you don't know before-hand how many times to iterate, then a while loop may be appropriate.<jupyter_code>#Find the first Fibonacci number that is larger than 1 billion

a=1
b=1
while a < 1000000000:
    temp=a
    a=b
    b=temp+a
print(a)<jupyter_output>1134903170<jupyter_text>List Comprehensions (somewhat advanced)List comprehensions provide a convenient shorthand to create a new list from an existing list by performing an operation on each member of the original list. The general syntax for a simple list_comprehension looks like:[python_expression_that_can_reference_var_name for var_name in list_name]Below is an example of using a list comprehension to create a list of the squares of an original list.<jupyter_code>my_list = [1,2,5,7,12,17]
[x*x for x in my_list]<jupyter_output><empty_output><jupyter_text>You could achieve the exact same effect with a for loop. The above list comprehension is a more compact way to express the below for loop:<jupyter_code>my_list = [1,2,5,7,12,17]
result_list = []
for elt in my_list:
    result_list.append(elt*elt)
result_list<jupyter_output><empty_output><jupyter_text>List Comprehensions with conditioning (somewhat advanced)You can also apply a filtering to each of the elements in the list comprehension. The general syntax looks like:[python_expression_that_can_reference_var_name for var_name in list_name if python_expression_conditional]The above looks confusing to look at in general terms, but here is a concrete example that may be more clear. We use a list comprehension to get the squares of a list of integers, but we filter out any "bad" data:<jupyter_code>my_unfiltered_list = [1,2,None, 5,7,12, 'twenty', 17]
[x*x for x in my_unfiltered_list if type(x) is int]<jupyter_output><empty_output><jupyter_text>The above list comprehension can be replicated, as below, by a for loop and if statements. Once you get the hang of it, the list comprehension is a more readable piece of code.<jupyter_code>my_unfiltered_list = [1,2,None, 5,7,12, 'twenty', 17]
result_list = []
for x in my_unfiltered_list:
    if type(x) is int:
        result_list.append(x*x)
result_list<jupyter_output><empty_output><jupyter_text>Example Loops1 - Count the number of even elements in a list Loop through my_list_1 and keep a counter of all the even numbers in the list. The code below shows how to do this using a For Loop and List Comprehension.<jupyter_code>my_list_1 = [252, 9, 258, 220, 249, 83, 195, 298, 228, 67, 233, 133, 280, 96, 53, 204, 
            247, 268, 115, 127, 215, 214, 221, 275, 224, 36, 292, 145, 150, 17, 93, 
            292, 206, 229, 189, 41, 246, 279, 158, 161, 90, 47, 195, 137, 171, 5, 
            206, 106, 58, 226, 140, 6, 29, 277, 192, 47, 296, 90, 19, 290, 235, 229, 
            26, 8, 220, 168, 294, 238, 138, 150, 13, 143, 209, 102, 192, 2, 140, 6, 99, 189
            ]

#Using a for loop
counter = 0
for elt in my_list_1:
    if elt % 2 == 0:
        counter = counter + 1
counter
#Using a list comprehension
len([x for x in my_list_1 if x%2==0])<jupyter_output><empty_output><jupyter_text>2 - Find Stocks with PE Ratio in a certain range Using the code below, you start with a dictionary of stocks and come up with a list of stocks that have a PE ratio between 10 and 15.<jupyter_code>my_dict_pe={'AXP':9,'VZ':10.2,'BA':None,'CAT':8.3,'JPM':7.9,
            'CVX':9.3,'KO':17.9,'DIS':19.1,'MRK':13.7,'MMM':13.3}

#code for list of PE stocks in range
screened_stocks=[]
for item in my_dict_pe.items():
    key,val = item
    if val is not None and val>=10 and val <=15:
        screened_stocks.append(key)
print(screened_stocks)<jupyter_output>['VZ', 'MRK', 'MMM']<jupyter_text>3 - Calculate the Market Value on a Portfolio Loop through the shares list and calculate the position value, multiplying number of shares by the price.<jupyter_code>shares = [8000, 3500, 14100, 2100, 1500, 7500, 4800, 2800, 3700, 8200, 900, 1300, 6200, 16200, 500, 2900, 5100, 5000, 10700, 1000, 1100, 16900, 800, 200, 2900, 1700, 500, 800]
prices = [60.02, 148.85, 37.76, 213.99, 193.59, 53.85, 123.21, 118.72, 116.74, 68.3, 113.39, 117.23, 130.4, 32.96, 134.45, 86.75, 139.33, 87.58, 38.19, 354.67, 141.34, 11.08, 309.89, 306.56, 19.93, 132.65, 92.92, 46.4]

### Your code here
position_values=[]
for i in range(len(shares)):
    position_values.append(shares[i] * prices[i])

print('Position Values: ', position_values)
print('Total Portfolio Value: ', sum(position_values))<jupyter_output>Position Values:  [480160.0, 520975.0, 532416.0, 449379.0, 290385.0, 403875.0, 591408.0, 332416.0, 431938.0, 560060.0, 102051.0, 152399.0, 808480.0, 533952.0, 67225.0, 251575.0, 710583.0000000001, 437900.0, 408633.0, 354670.0, 155474.0, 187252.0, 247912.0, 61312.0, 57797.0, 225505.0, 46460.0, 37120.0]
Total Portfolio Value:  9439312.0
{'fraction_non_alphanumeric': 0.09727219965177017, 'fraction_numerical': 0.10295995356935578, 'mean_word_length': 4.594805194805195, 'pattern_counts': {'":': 0, '<': 54, '<?xml version=': 0, '>': 52, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '101750', 'license': 'MIT', 'n_tokens_mistral': 3641, 'n_tokens_neox': 2896, 'n_words': 1179, 'path': 'Learn Python Loops.ipynb', 'repo_name': 'HDVI/AlphaWaveData', 'size': '8615'}