Skip to content
Snippets Groups Projects
Commit 198274c4 authored by cprutean's avatar cprutean
Browse files

Upload New File

parent 5ce92506
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Loops and Looping
To get into real programming we have to look at loops; here we have a
*block* of code that is repeated either a set number of times (`for` loops) *or* until some condition is reached (`while` loops).
#### Key Point
The use of *loops* can often be a significant hurdle for new
programmers but it is absolutely key to programming. Any “non-trivial”
program contains loops, often many of them, and is the key to a
computer’s main strength of “doing the same simple thing over and over
again…” very fast.
## Fixed length loops
First we will start with the simplest case of fixed length loops. Assume
we want to print out values of $\cos(\theta)$ in the range
$0\rightarrow2\pi$ using a `for` loop. Consider the piece of code:
%% Cell type:code id: tags:
``` python
import math
points = 50
dt = 2.0*math.pi/points
for i in range(0,points):
theta = dt*i
value = math.cos(theta)
print("theta is : " + str(theta) + " cos(theta) : " + str(value))
print("End of loop")
```
%% Output
theta is : 0.0 cos(theta) : 1.0
theta is : 0.12566370614359174 cos(theta) : 0.9921147013144779
theta is : 0.25132741228718347 cos(theta) : 0.9685831611286311
theta is : 0.3769911184307752 cos(theta) : 0.9297764858882513
theta is : 0.5026548245743669 cos(theta) : 0.8763066800438636
theta is : 0.6283185307179586 cos(theta) : 0.8090169943749475
theta is : 0.7539822368615504 cos(theta) : 0.7289686274214116
theta is : 0.8796459430051422 cos(theta) : 0.6374239897486896
theta is : 1.0053096491487339 cos(theta) : 0.5358267949789965
theta is : 1.1309733552923256 cos(theta) : 0.42577929156507266
theta is : 1.2566370614359172 cos(theta) : 0.30901699437494745
theta is : 1.3823007675795091 cos(theta) : 0.18738131458572452
theta is : 1.5079644737231008 cos(theta) : 0.0627905195293133
theta is : 1.6336281798666925 cos(theta) : -0.0627905195293134
theta is : 1.7592918860102844 cos(theta) : -0.18738131458572482
theta is : 1.884955592153876 cos(theta) : -0.30901699437494756
theta is : 2.0106192982974678 cos(theta) : -0.4257792915650727
theta is : 2.1362830044410597 cos(theta) : -0.5358267949789969
theta is : 2.261946710584651 cos(theta) : -0.6374239897486897
theta is : 2.387610416728243 cos(theta) : -0.7289686274214117
theta is : 2.5132741228718345 cos(theta) : -0.8090169943749473
theta is : 2.6389378290154264 cos(theta) : -0.8763066800438636
theta is : 2.7646015351590183 cos(theta) : -0.9297764858882515
theta is : 2.8902652413026098 cos(theta) : -0.9685831611286311
theta is : 3.0159289474462017 cos(theta) : -0.9921147013144779
theta is : 3.1415926535897936 cos(theta) : -1.0
theta is : 3.267256359733385 cos(theta) : -0.9921147013144779
theta is : 3.392920065876977 cos(theta) : -0.9685831611286311
theta is : 3.518583772020569 cos(theta) : -0.9297764858882512
theta is : 3.6442474781641603 cos(theta) : -0.8763066800438635
theta is : 3.769911184307752 cos(theta) : -0.8090169943749472
theta is : 3.8955748904513436 cos(theta) : -0.7289686274214116
theta is : 4.0212385965949355 cos(theta) : -0.6374239897486895
theta is : 4.1469023027385274 cos(theta) : -0.5358267949789963
theta is : 4.272566008882119 cos(theta) : -0.42577929156507216
theta is : 4.39822971502571 cos(theta) : -0.30901699437494756
theta is : 4.523893421169302 cos(theta) : -0.18738131458572463
theta is : 4.649557127312894 cos(theta) : -0.06279051952931321
theta is : 4.775220833456486 cos(theta) : 0.06279051952931372
theta is : 4.900884539600078 cos(theta) : 0.18738131458572513
theta is : 5.026548245743669 cos(theta) : 0.30901699437494723
theta is : 5.152211951887261 cos(theta) : 0.4257792915650726
theta is : 5.277875658030853 cos(theta) : 0.5358267949789968
theta is : 5.403539364174445 cos(theta) : 0.63742398974869
theta is : 5.529203070318037 cos(theta) : 0.7289686274214119
theta is : 5.6548667764616285 cos(theta) : 0.8090169943749478
theta is : 5.7805304826052195 cos(theta) : 0.8763066800438636
theta is : 5.906194188748811 cos(theta) : 0.9297764858882515
theta is : 6.031857894892403 cos(theta) : 0.9685831611286312
theta is : 6.157521601035995 cos(theta) : 0.9921147013144779
End of loop
%% Cell type:markdown id: tags:
Looking at this in detail:
- Line 1: `points` is an `int`, in this case the number of points we want to calculate in between $0\rightarrow2\pi$
- Line 2: is the separation between each value of $\theta$ we wish to
calculate.
- Line 3: the start of the `for` loop. It says: create an `int` variable `i` and while it is the range $0\rightarrow49$, execute the loop:
- It will *stop* before 50, so at 49.
- The `:` at the end of the line is essential and is part of the
syntax.
> #### Range function
The range function has the full syntax
```python
range(start,end,step)
```
where `start` is the starting integer, `end` the termination integer and the *optional* argument `step` the amount the value is incremented each time. If `step` is not given, it defaults to 1.
> All arguments *must* be `int`, and the loop will terminate *before*
reaching the `end` value.
- Line 4 to 6: the indented code is *inside* the loop:
- Calculate $\theta$ by scaling `i` where `dt` is the separation between values.
- Calculate `value`, being $\cos(\theta)$.
- Print out the value of $\theta$ and of $\cos(\theta)$ to the
screen.
It will do this 50 times.
- Line 7: Print `End of Loop` when the loop is finished; it will only print this
once.
### Key Point
Note the most important bits of syntax here are
- that the body of the loop, (lines 4,5, & 6), *must* be indented by
*exactly 4 spaces*.
- the loop variable `int` in that is automatically incremented each time round the loop.
- that the number of times the loop is exected is determined at the
start (even if the loop variable in changed within the body of the
loop).
## Loop access of lists
One of the main applications of loops is to access the elements of a
list, here we will look at two routes, the first conceptually simpler.
Assume that the list `mydata` contains `float`s, its length is given by `len(mydata)` so if we want to sum up the values squared of the elements in `mydata` we could write
%% Cell type:code id: tags:
``` python
total = 0.0
for i in range(0,len(mydata)):
total = total + mydata[i]**2
print("The total of mydata squared is : " + str(total))
```
%% Output
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-3cb76652cfbb> in <module>
1 total = 0.0
----> 2 for i in range(0,len(mydata)):
3 total = total + mydata[i]**2
4
5 print("The total of mydata squared is : " + str(total))
NameError: name 'mydata' is not defined
%% Cell type:markdown id: tags:
which in detail does the following:
- Line 1: create a variable `total` and set its initial value to zero.
- Line 2: start of loop from 0 to `len()` of list; note again `i` will run from $0\rightarrow {\tt len()} - 1$
- Line 3: add the square of the `i`th elements of `mydata` to `total`; note the indentation.
- Line 5: at the end of the loop print out the answer.
> #### Missing Line 4
Here Line 4 is *intentionally left blank*, you can insert extra blank lines anywhere in your code and leaving a blank line at the end of a loop makes the code more readable and easier to understand.
> Remember: white-space is *free*, use it to make your code readable, it will save you much time and effort when trying to find bugs.
### Key Point
Here again the key points of this loop are
- the number of times the loop is executed is determined as the start,
it is `len(mydata)`.
- the loop index `i` is automatically incremented by $+1$ every time round the loop.
- the largest value that `i` takes is $len(mydata)-1$ which is the index of the *last* element in the list.
However since accessing lists like this is such a common operation there
is a more compact syntax to do the same thing; take the following piece
of code.
%% Cell type:code id: tags:
``` python
total = 0.0
for d in mydata:
total = total + d*d
print("The total of mydata squared is : " + str(total))
```
%% Cell type:markdown id: tags:
- Line 1: create variable `total` and set it to zero.
- Line 2: start of `for` loop, here the variable `d` is set to the value of each of the elements of `mydata` in turn.
- Line 3: add the value of `d` squared to `total`.
- Line 5: at the end of the loop, print out the final value.
Both of these pieces of code will do the same thing, but the second is
shorter, more computationally efficient and in `Python` style, but somewhat more difficult to understand.
> #### Being Pythonic
Being “Pythonic” is a statement you will find all over
the web; it means doing something in “python style” which usually means
using a programming method or syntax unique to `Python` that is not available in other languages. This can be “good” as in the alternative method to access lists since it is shorter and more efficient, but can also be “bad” since some of the Pythonic style is very compact and difficult to work out what it is actually doing. It is also often used to push style over function.
> You will find must heated *debate* about this on the computing forums
often by people who’s knowledge is questionable, but you should
concentrate on getting your programs to work and understand what they
are doing first. Worry about making them “Pythonic” as you gain
experience. Do NOT copy down “magic recipes” from forums that you don’t
understand and may not do what you want / expect.
## The `while` loop
The other looping construct is when at the start of the loop we **do not
know** how many times the loop is to be executed, for example consider
the code below:
%% Cell type:code id: tags:
``` python
x = 0
while x < 100 :
x = x + random.randint(1,6)
print("Final value of x is : " + str(x))
```
%% Output
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-cbfe5d858a1f> in <module>
1 x = 0
2 while x < 100 :
----> 3 x = x + random.randint(1,6)
4
5 print("Final value of x is : " + str(x))
NameError: name 'random' is not defined
%% Cell type:markdown id: tags:
so looking at this in detail,
- Line 1: set the initial value of `x`
- Line 2: start of `while` loop, the body of the loop will be executed while the logical statement $x < 100$ is `True`
In this type of loop the programmer is responsible for updating the
termination condition, the `x` in this case. This type of loop is most often used in iterative methods, for example calculating the roots of an
equation to a particular accuracy or the position of projectile.
This type of loop is the key to solving Checkpont 5 in a couple of
weeks.
> #### Getting stuck
The “danger” of the `while` loops is forgetting to update the
variable that control the termination condition. The loop then never
terminates and the program “hangs” going round-and-round “for ever”. If
(when) this happens
- Type `Cntl-C` (both keys at once) which will interrupt the program and tell you where it was in the code.
- If you can’t see the problem, print out the termination variable in
the loop to see what is happening.
## The `break` statement
An important concept associated with loops is the ability to “break out
off a loop early”, which overrides the normal loop termination
condition, so for example we could have:
%% Cell type:code id: tags:
``` python
total = 0
while total < 100 :
x = <function that sets x>
if x < 0 :
break
else :
total = total + x
print("End of loop")
```
%% Output
File "<ipython-input-6-cb0d11525ce0>", line 3
x = <function that sets x>
^
SyntaxError: invalid syntax
%% Cell type:markdown id: tags:
so in detail
- Line 1: set `total` to zero
- Line 2: start of `while` loop, which should run until $total < 100$
- Line 3: code that calculates a value for `x`
- Line 4 & 5: Tests if the value of `x` is negative, and if it is `break` the loop, so jump straight to the end of the loop *now*.
- Line 6 & 7: if `x` is positive, then add to `total` and continue with the loop.
You should use the `break` statement with care; its proper use is to catch errors or unexpected conditions. Using it as a part of algorithm often results in code that is hard to read.
A common programming *trick* is to deliberately put a program into an
infinite loop and then use the `break` statement as the exit, for example:
%% Cell type:code id: tags:
``` python
while True :
x = \<function to set x>
if x > 100:
break
print("End of loop")
```
%% Cell type:markdown id: tags:
Here the `while` loop will run *forever* and your program will only exit this loop when `x` has been set to 100 (or more).
This is a construct that is often used in interactive programs that keep
taking “command” for example keeps asking for files to process or
programs with a “graphical user interface” (GUI), but should be used
with care in general programming since it difficult to debug and work
out what is really happening.
> **Code Examples**
- Loop to terminal using for range :
- Loop to list using for range :
- Loop to list using while :
- Guessing Game using `while` and `break`:
> You should download these examples and "play" with them.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment