Introduction to Loops

In [ ]:
import numpy as np

Problem 1

Write code to print the numbers 0 to 4 on each line below.


In [ ]:


  • Okay, let's keep going to 10000...(!?)


  • Loops in programing are used to simplify repetative work.
  • Above, each line is a print statement.
    • The only thing different on each line is the number we are printing.
  • We can write a loop statment to do the above problem as follows
In [ ]:


  • What are the parts of this: list them?
  • i can be any variable, not just "i"
  • Is there anything weird or unexpected here?

Problem 2

  • We can put any code in the for loop
    • Variables, functions, expressions, math, etc.
  • We can put variables outside of the loop that are available inside of the loop

For the ideal gas law, pressure is given by $$P = nRT/V$$

  • n = 1 kmol
  • R = 8314 J/kmol*K
  • T = 300 K

For V = 2, 3, 4, 5, ... 20, use a loop to find and print the values of P for each V.


In [ ]:


  • What if you wanted V to not step by integers?
    • Step by 2? Step by 5?
    • Step by 0.2?

Problem 3

Add all the numbers from 0 to 100

  • Before you start the code, think about what you would do if solving this in your head?
    • How do you start?
    • What things do you keep track of?
    • What variables to use?
    • What is the loop syntax?
    • How do variables interact with the loop?
  • Think through the process of the problem to the solution
  • Talk to your neighbor
  • If you've solved it, help your neighbor.


In [ ]:

Nested loops

  • We can put any code in a for loop. Even another loop.
  • Look at the code below.
  • Before running it, think of what you expect to see.
    • Now run it and compare. Did you get what you thought you would?
In [ ]:
for i in range(3):
    for j in range(4):
        print(f"  j={j}")
  • Note, each time through the top (outer) loop, everything inside is done.
  • This means the whole inner loop is computed for each outer loop.
  • Think of an actual application for a nested loop.

Problem 4a

  • Given the following function $$f(x) = x^2 - 3,$$ we can use Newton's method to find $x$ for $f(x)=0$.

  • Recall, Newton recurrence formula: $$x_{new} = x_{old} - \frac{f(x_{old})}{f^\prime(x_{old})}$$

We solved this previously in Excel

  • Open Excel and solve this problem.
  • Think about the steps involved, how we set it up.
  • Use the simplest method possible.


Excel Python
cell for guess ??
Newton equation in terms of x cell
A2 - (A2^2-3)/(2*A2)
repeat: fill down ??

Problem 4b

Now solve in Python using loops

  • Try to write the simplest solution you can think of with as few lines of code as possible.
  • We want 3 decimal places of accuracy.
  • Consider:
    • What variables are needed?
    • How to setup and use the loop.
    • What to print and where?


In [ ]:


  • Variable i is not being used, it is just for convenience in creating the loop.
  • Note how x is used on both sides of the equation. It is reused.

Explicitly write out the four steps

  • We don't have to code it from top to bottom...
  • Compare to Excel
Excel Python
cell for guess variable for x
Newton equation in terms of x cell
A2 - (A2^2-3)/(2*A2)
Newton equation in terms of x
x = x - (x**2-3)/(2*x)
repeat: fill down repeat: wrap in loop
In [ ]:
# step 1:

# step 2:

# step 3:

# step 4:

Problem 4c

Redo Solution 1 using functions for $f(x)$ and $f^\prime(x)$.

  • Recall: we discussed functions two classes back.
In [ ]:

Problem 4d

  • Now, to get to three decimal places we only needed 3 iterations.
  • But we didn't know this at the beginning, so we guessed the number of iterations.
    • If 6 wasn't enough, we would do more.
  • This guess and check is not very efficient.

Modify the code above to do just the right number of iterations.

  • What Python features do you need to use?
  • How do you decide when you are done?
  • Talk with your neighbor.


In [ ]:


In [ ]: