count = 0
while count < 100:
    count += 1
count

"""
Explanation: Some meta comments

My teaching feedback
References to the future are mostly just abstract without a mental map.
Same is true with references to other programming languages if you are not
 familiar with them.
Focus on one teaching object at a time.
Devices in class room
Why tutorials?

Recap: while loops and lists
What does it do?
End of explanation
"""


#
# Initializations first
#
massRatioList = []         # Creates an empty list
massRatioValue = 1   # For the conditional
massRatioMax = 15   # Also for the conditional
#
# And the while loop:
# 
while massRatioValue <= massRatioMax:  # Note the colon!
    massRatioList.append(massRatioValue)   # Note the indentation!
    massRatioValue += 1

print(massRatioList)
print(massRatioValue)

"""
Explanation: Q. What would this program print?
Rather than type in long lists, we can use while loops:
End of explanation
"""


for massRatio in massRatioList:  # Note the colon!
    print(massRatio) # Note the indent!

massRatio

for massRatio in massRatioList:  # Note the colon!
    print('massRatioList element = {}'.format(massRatio)) # Note the indent!

print('\nmassRatioList has {} elements!'.format(len(massRatioList)))
massRatio

"""
Explanation: Today: for loops and lists, list comprehensions, tuples
For loops operate on elements in a list.
Basic structure:
python
for &lt;element&gt; in &lt;list&gt;:
    &lt;do something with element&gt;  
<element> will be a variable name assigned to 
individual elements in <list>
as opposed to while loops:
python
while &lt;condition is True&gt;:
    &lt;do something&gt;
End of explanation
"""


# First, initialize variables
G       = 6.67e-11           # Grav. const.
mEarth  = 5.97e24            # Earth mass
mPerson = 70                 # Person mass 
radius  = 6.37e6             # Earth radius

massRatioList  = []          # Creates an empty list
massRatioValue = 1           # First mass ratio value
massRatioMax   = 15          # Last mass ratio value

# Create a list of mass ratios using a for loop
for massRatioValue in range(massRatioValue, massRatioMax + 1):   # Note the "+ 1"
    massRatioList.append(massRatioValue)

# Make a header for the table
print("# Mass-Ratio\tForce")

# Calculate the force for each mass ratio
for massRatio in massRatioList:
    force = G * massRatio * mEarth * mPerson / radius**2  

    # print contents of table line-by-line
    print("{}\t\t{:.2f}".format(massRatio, force))

"""
Explanation: Note that you do not have to 
* know the length of the list
* define a walking index.
Let's use a for loop to make a table of mass ratios and gravitational forces:
End of explanation
"""


for massRatio in massRatioList:
    print(massRatio)

"""
Explanation: Note, how the force value automatically became a float, how it should be.
While loop implementation of a for loop
A simple for loop:
End of explanation
"""


index = 0   # Remember that the index starts with zero!
while index < len(massRatioList):
    print(massRatioList[index])
    index += 1

"""
Explanation: Can also be implemented as a while loop:
End of explanation
"""


index

"""
Explanation: This is a little less compact, but very intuitive.
Q. What is the value of index at the end (trace it!)?
End of explanation
"""


print?

index = 0   # Remember that the index starts with zero!
while index < len(massRatioList):
    print(massRatioList[index], end=' ')
    index += 1

"""
Explanation: Interlude: make print work side-ways
Q. How could I learn about the ability's of print?
The built-in help system
IPython and therefore its kernel here in Jupyter has a built-in help system.
It depends on code author to fill in these docstrings (I show you how later.)
Enter help system by calling object?. In Jupyter a sub-window appears. When done reading you leave it by pressing q or clickin the x in the upper right corner.
Example: Learn how to make print print side-ways.
End of explanation
"""


mygenerator = range(10)  # note how the print out also shows the default 0 starting value.
print(mygenerator)
mylist = list(mygenerator)
mylist

range?

"""
Explanation: The "range" function
An easy way to populate lists!
(In case you haven't noticed, there are already Python
functions to do most things!)
Syntax:  range(n)
  generates integers 0, 1, 2, ... n-1
Syntax: range (start, stop, step) 
  generates from start to stop-1 with stepsize = step
  If step is not specified, it is assumed to be 1.
Python 3 to 2 difference:
Python 3 returns a generator for the list, not the list itself.
That means, if you want to see the list, it needs to be fully generated. To enforce this, convert the generator with the list funcion:
End of explanation
"""


print(list(range(-10, 2, 2)))
print(list(range(-5)))

"""
Explanation: Q. What does this generate?
End of explanation
"""


list(range(0, -5))

"""
Explanation: Q. Why is the last list empty?
A. Because the default values don't match.
Calling range() with only 1 value means it is intepreted as STOP value, with START assumed to be 0 and STEP to be +1. 
So, 
python
range(-5) 
is the same as 
python
range(0,-5,1)
See why the list is empty?
Does this work?
End of explanation
"""


list(range(0, -5, -1))

"""
Explanation: No, because the last default value is -1!
We wanted:
End of explanation
"""


print(list(range(-10, 0, 2)))
len(range(-10, 0, 2))

"""
Explanation: For fun: using a function as an argument:
End of explanation
"""


massRatioList = []
for massRatio in range(1, 11, 1):
    massRatioList.append(massRatio)
massRatioList

"""
Explanation: For our mass ratio list example:
End of explanation
"""


massRatioList = list(range(1,11))
massRatioList

"""
Explanation: Q. What could we simplify now, knowing about the range function?
Use range() for the massRatioList itself!
End of explanation
"""


for i in range(len(massRatioList)):
    print(i, massRatioList[i])

"""
Explanation: The "enumerate" function
Often, you'll want the indices and the list element values, to steer or access other values in other lists. Python has a short-cut function for this sort of thing: enumerate
Note: This is better Python style than to create your index yourself and use that to access elements in the array.
So, this is bad(-ish):
End of explanation
"""


for i, massRatio in enumerate(massRatioList):  # enumerate returns both the index and the item
    print(i, massRatio)

 # Equivalently (but not exactly the same):

for stuff in enumerate(massRatioList):
    print(stuff[0], stuff[1])

"""
Explanation: This is better:
End of explanation
"""


# Notice the parentheses.
# What kind of variable type is stuff?

type(stuff)

print(stuff)

"""
Explanation: Python tries to be helpful here! As learned above, enumerate returns both the index and the current item for the loop.
It could have thrown you an error, because you only catch one value. Instead, in Python, it stores too many items in a new compound item:
End of explanation
"""


a = [1,2]
a

a[0] = 3
a

a = tuple(a)
a

print(t[0])

t[0] = 8

"""
Explanation: Tuples are the so called immutable versions of lists. Useful if you want to make sure you don't accidently change them while using them:
End of explanation
"""


massRatios = range(5)

for massRatio in massRatios:
    print(massRatio, end=' ')

massRatios  = []        # Initialize.Why? If it's not there, can't append!
numElements    = 10        # Number of elements
massRatioMin   = 1      # Minimum mass ratio
massRatioMax   = 10      # Maximum mass ratio
massRatioDelta = (massRatioMax - massRatioMin) / (numElements - 1)   # Mass ratio increment

for index in range(0, numElements):
    massRatio = massRatioMin + index * massRatioDelta
    massRatios.append(massRatio)
    print(index, massRatio)

"""
Explanation: Processing lists simultaneously with for loops
The following construction is a bit lengthy (with 3 loops),
but it shows how multiple lists (massRatioList and forceList) 
can be processed simultaneously with for loops
Good mnemonic for lists: Use PLURAL!
End of explanation
"""


G         = 6.67e-11         # Gravitational constant
mEarth    = 5.97e24          # Earth mass
mPerson   = 70               # Person mass 
radius    = 6.37e6           # Earth radius
forces = []               # Empty list -- I don't have to specify its length

for massRatio in massRatios:
    force = massRatio * G * mEarth * mPerson / radius**2  
    forces.append(force)

print("Index\tM_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for index in range(len(massRatios)):
    massRatio = massRatios[index]
    force = forces[index]
    print('{}\t{:.1f}\t{:.2f}'.format(index, massRatio, force))

a = range(1,11)
b = range(21,31 )

list(a)

list(b)

for itema, itemb in zip(a,b):
    print(itema, itemb)

"""
Explanation: Now, calculate the forces using massRatios:
End of explanation
"""


print("Index\tm_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for i, massRatio, force in enumerate(zip(massRatios, forces)):
    print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))

print("Index\tm_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for i in enumerate(zip(massRatios, forces)):
    print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))

print("Index\tm_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for i, (massRatio, force) in enumerate(zip(massRatios, forces)):
    print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))

"""
Explanation: Above the index is not used for calculations, therefore there is a better way to do it: Use zip to combine lists in a 'zipper' like fashion.

The automatic unpacking of tuples can never have too many receivers, but it can too few!
End of explanation
"""


mylist = []
for i in range(10):
    mylist.append(i)
mylist

"""
Explanation: List comprehension
End of explanation
"""


mylist = [i**2 for i in range(10)]
mylist

numElements = 10

massRatios = [1.0 + index for index in range(numElements)]          # list comprehension!
forces     = [massRatio * G * mEarth * mPerson / radius**2\
              for massRatio in massRatios]

"""
Explanation: can be written as:
End of explanation
"""


print("Mass Ratio\tForce")  # note that "Mass Ratio" is so long, it swallows one \t from below.

for massRatio,force in zip(massRatios, forces):
    print('{:.1f}\t\t{:.2f}'.format(massRatio, force))

"""
Explanation: Wow, that is compact!  Two lines!  Did it work?
End of explanation
"""


%%timeit  # this is called "IPython magic"
massRatios = [0] * numElements
forces     = [0] * numElements

#  Using a single for loop, populate the two lists
for index in range(len(massRatios)):
    #  Calculate the mass ratio
    massRatios[index] = massRatioMin + index * massRatioDelta

    #  Calculate the force
    forces[index] = massRatioList[index] * G * mEarth * mPerson / radius**2


%%timeit?

%%timeit
numElements = 10

massRatios = [1.0 + index for index in range(numElements)]          # list comprehension!
forces     = [massRatio * G * mEarth * mPerson / radius**2 for massRatio in massRatioList]

"""
Explanation: Learn how fast your code works
End of explanation
"""


