Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • cprutean/sciprog2024
  • pclark3/sciprog2024
2 results
Show changes
Commits on Source (20)
%% Cell type:markdown id: tags:
We have seen in that functions basically *do what you expect*, and in
particular the variables *inside* the function are seperate from those
in the program. This is true for the basic build-in types (, , and ),
but you have to be *very careful* when you pass s into functions.
Consider what happend in the following code where the function sets a
given with random numbers.
def set_random_list(lst): """ Function to set a list full of random
numbers. """ for i in range(0,len(lst)): lst\[i\] = random.random()
def main(): xdata = \[0.0\]\*100 set_random_list(xdata)
main()
Now consider what happens,
- in the program we create a list of 100 s, all set to zero,
- then this is passed to the function the is sent to the function,
- inside the function the data *held* in the is the same as the data
in the , so if you change the values of the elements of the list
inside then they *will* change in .
- in , after the call to the *elements* of the list will be set to
random numbers.
This operation of functions *is* typically what you want to happen, but
you have to be very careful that you really intend to modify the
contents of a list inside the function.
The way that numbers operate need a bit of through on how they work, if
you have a function as below that a ,
def complex_value_compare( a , b): if a.real \> b.real and a.imag \>
b.imag: return a + b else: return a - b
then this will work exactly as you expect and you can *read* the real
and imaginary parts of the arguments with the and syntax. *BUT* beacuse
of the way the number is passed you are not able to write to the real
and imaginary parts by this route, this means that althought a complex
number looks like a of two numbers, it cannot be changed inside a
function.
webonly
The There is a variant on the list called a which holds multiple
elements just like a , is indexed by the same syntax for read *but*
cannot be wrtten to, so its values are *fixed*. This is not frequently
used in normal *user* programs, but is used inside complex libraries to
implement constants.
You have now completed sufficient to attempt which is the last
checkpoint of the course.
%% Cell type:markdown id: tags: %% Cell type:markdown id:e766b8cd tags:
This pages gives recipes on how to get working on your own machine. It This pages gives recipes on how to get working on your own machine. It
is a based on *best effort* local experience and comes with no support. is a based on *best effort* local experience and comes with no support.
While we encourage you to get working on your own machine and *play*, While we encourage you to get working on your own machine and *play*,
remember that we will **only** marks checkpoints on the CPLab machines remember that we will **only** marks checkpoints on the CPLab machines
and not your own laptops. and not your own laptops.
You must transfer any code to the CPLab system (by USB Key or e-mail), You must transfer any code to the CPLab system (by USB Key or e-mail),
and make sure it works there before getting it marked. and make sure it works there before getting it marked.
The best supported and comprehensive environments is currently Anaconda The best supported and comprehensive environments is currently Anaconda
This is free to download and install for *Windows* *Mac* or *Linux*. This is free to download and install for *Windows* *Mac* or *Linux*.
This inclues a full 3.7 kit, the IDE *Spyder* and all the additional This inclues a full 3.7 kit, the IDE *Spyder* and all the additional
libraries to could even want. It also includes *Juypter* and libraries to could even want. It also includes *Juypter* and
*Juypter-Lab* and *VS Code* which you will not need in this course. *Juypter-Lab* and *VS Code* which you will not need in this course.
The download and install is fully doumented in the above and should The download and install is fully doumented in the above and should
basically *just work*. The download is very large and expands to a basically *just work*. The download is very large and expands to a
couple of couple of GByte, but this is well with the capability of most couple of couple of GByte, but this is well with the capability of most
modern laptops / desktops. modern laptops / desktops.
For *Windows* or *Mac* user we strongly recommend the *Spyder* For *Windows* or *Mac* user we strongly recommend the *Spyder*
development environment; this given an editor to edit code and a console development environment; this given an editor to edit code and a console
to run code, this is actually a *IPython* console, but if you just *run* to run code, this is actually a *IPython* console, but if you just *run*
it will work. *Spyder* also reads and write files is standard text so it will work. *Spyder* also reads and write files is standard text so
you can easily transfer to/from CPLab with USB key. you can easily transfer to/from CPLab with USB key.
The *Spyder* environment has also been installed on the CPLab, but at The *Spyder* environment has also been installed on the CPLab.
the moment it is still being developed, so it not recommended yet.
The Mac is fundamentally a Unix machine, so you can tailor it to looks The Mac is fundamentally a Unix machine, so you can tailor it to looks
very much like the CPLab Linux machines. Do do this you have t do the very much like the CPLab Linux machines. Do do this you have t do the
following: following:
## Install the X11 environment ## Install the X11 environment
This is not installed by default, but is a free download from the Mac This is not installed by default, but is a free download from the Mac
Store and will autoinstall. Store and will autoinstall.
- In the Finder select Applications $\rightarrow$ Utilities - In the Finder select Applications $\rightarrow$ Utilities
$\rightarrow$ X11. $\rightarrow$ X11.
If this is installed it will start, if not it will take you to the If this is installed it will start, if not it will take you to the
Apple Store and will take you through the install, this is a large Apple Store and will take you through the install, this is a large
install as it includes other programming development tools. install as it includes other programming development tools.
- This is needed to display the Matlibplot graphics and it also gives - This is needed to display the Matlibplot graphics and it also gives
you an *xterminal* which is just about identical to the terminal on you an *xterminal* which is just about identical to the terminal on
the CPLab machines. You start this click on the X11 logo in the the CPLab machines. You start this click on the X11 logo in the
Toobar, then Aplication $\rightarrow$ Terminal in the topbar. Toobar, then Aplication $\rightarrow$ Terminal in the topbar.
X11 is needed for all the orther free Unix utilities you may also wish X11 is needed for all the orther free Unix utilities you may also wish
to install, for example XMGrace, xfig, gnuplot. You will find there on to install, for example XMGrace, xfig, gnuplot. You will find there on
your favourite download site. your favourite download site.
## Installing an Editor ## Installing an Editor
The default version of emacs in the Mac is *very limited* and only works The default version of emacs in the Mac is *very limited* and only works
within the terminal window, so you will want to install something within the terminal window, so you will want to install something
*better*. Here you have choice… *better*. Here you have choice…
Emacs for X11: This gives you the same emacs as on the CPLab. Emacs for X11: This gives you the same emacs as on the CPLab.
- Download from for example [a](http://emacsformacosx.com/)s a dmg and - Download from for example [a](http://emacsformacosx.com/)s a dmg and
do the install. do the install.
Emacs for Aqua: This gives you emacs but running via the Mac OSX own Emacs for Aqua: This gives you emacs but running via the Mac OSX own
window system (Aqua), rather than X11. window system (Aqua), rather than X11.
- Download from [.](http://aquamacs.org/) - Download from [.](http://aquamacs.org/)
To run either of these select them from the Applications or Launchpad To run either of these select them from the Applications or Launchpad
screen and then Open File. If you want to run from the terminal as you screen and then Open File. If you want to run from the terminal as you
do in the CPlab, you will have to learn about `.bachrc` files and do in the CPlab, you will have to learn about `.bachrc` files and
`alias`, ask if you want to go there. `alias`, ask if you want to go there.
Other Editors There are *many* other editors, play, talk to friends etc; Other Editors There are *many* other editors, play, talk to friends etc;
but remember some require *real money* or have limited *free trial* but remember some require *real money* or have limited *free trial*
periods after which you have to pay! periods after which you have to pay!
A useful alternative is Xcode which is the full Apple development A useful alternative is Xcode which is the full Apple development
environment which is free to download from the Mac Store. It is *huge* environment which is free to download from the Mac Store. It is *huge*
and really designed to develop apps for *iPad*, *iPhone*, *iWatch* etc, and really designed to develop apps for *iPad*, *iPhone*, *iWatch* etc,
but it will also work as a simple editor. xCode is however very but it will also work as a simple editor. xCode is however very
resource intensive and it only really works on a new fast Mac with lots resource intensive and it only really works on a new fast Mac with lots
of memory, it also takes up about 3 Gbyte of disc! of memory, it also takes up about 3 Gbyte of disc!
If you are already running Linux on your own machine then you already If you are already running Linux on your own machine then you already
have everything to need, or can simply add it with what ever package have everything to need, or can simply add it with what ever package
manager come with your distribution. Here you also have an almost manager come with your distribution. Here you also have an almost
infinite choice of editors, but again most people will want to infinite choice of editors, but again most people will want to
`emacs-X11` on their system. `emacs-X11` on their system.
Note that some Linux distributions that follow the newest updates are Note that some Linux distributions that follow the newest updates are
now using as the default, for example Fedora, but if you are that close now using as the default, for example Fedora, but if you are that close
to the *bleeding*-edge you will already know this ! to the *bleeding*-edge you will already know this !
......
%% Cell type:markdown id:2e25586e tags: %% Cell type:markdown id:2e25586e tags:
# More on Functions # More on Functions
In the section on basic functions, [Basic Functions](basicfunctions.ipynb), we considered the simple case where a function took a number of arguments and returned a single *value*, typically a `float`. We now want on extend this to look at more complex use of functions. In the section on basic functions, [Basic Functions](basicfunctions.ipynb), we considered the simple case where a function took a number of arguments and returned a single *value*, typically a `float`. We now want on extend this to look at more complex use of functions.
## Returning more than one value ## Returning more than one value
*Functions* can be more flexible than just returning *a value*. Consider *Functions* can be more flexible than just returning *a value*. Consider
writing a *function* that when called will return a random point in writing a *function* that when called will return a random point in
three dimensions inside a sphere of a given radius. Consider the code three dimensions inside a sphere of a given radius. Consider the code
below: below:
```python ```python
import random import random
def random_point_in_sphere(radius): def random_point_in_sphere(radius):
""" """
Function to get a random point within a sphere of radius a Function to get a random point within a sphere of radius a
return floats x,y,z return floats x,y,z
""" """
while True: while True:
x = random.uniform(-radius,radius) x = random.uniform(-radius,radius)
y = random.uniform(-radius,radius) y = random.uniform(-radius,radius)
z = random.uniform(-radius,radius) z = random.uniform(-radius,radius)
if x*x + y*y + z*z <= radius*radius: if x*x + y*y + z*z <= radius*radius:
break break
return x,y,z return x,y,z
def main(): def main():
<....> <....>
rad = 10.0 rad = 10.0
px, py, pz = random_point_in_sphere(rad) px, py, pz = random_point_in_sphere(rad)
<....more code> <....more code>
dx, dy, dz = random_point_in_sphere(1.0) dx, dy, dz = random_point_in_sphere(1.0)
<....> <....>
``` ```
Now looking at this in detail: Now looking at this in detail:
1. Define a function `random_point_in_sphere()` that takes single parameter being the `radius` of the sphere. 1. Define a function `random_point_in_sphere()` that takes single parameter being the `radius` of the sphere.
2. Inside the function go round a loop forming a point `x,y,z` at random and checking if the point is inside a sphere of the specified `radius`. 2. Inside the function go round a loop forming a point `x,y,z` at random and checking if the point is inside a sphere of the specified `radius`.
3. Then `break` from the loop once you have a point, so after the loop `x,y,z` gives a random point within a sphere (which is what you want). 3. Then `break` from the loop once you have a point, so after the loop `x,y,z` gives a random point within a sphere (which is what you want).
4. Then `return` the three values as a `list`. 4. Then `return` the three values as a `list`.
5. In the `main()` program you can now call your *function* and return the values to a specifed list of three variables, e.g. `px,py,pz`. 5. In the `main()` program you can now call your *function* and return the values to a specifed list of three variables, e.g. `px,py,pz`.
This starts to shown the power of using functions, it removes the need to have to code for forming the random point in your `main()` program, and also you can call it as many times as you like in `main()` with different radius values. This starts to shown the power of using functions, it removes the need to have to code for forming the random point in your `main()` program, and also you can call it as many times as you like in `main()` with different radius values.
> #### return of a list > #### return of a list
Since the function `random_point_in_sphere()` returns a list, an alternative call is: Since the function `random_point_in_sphere()` returns a list, an alternative call is:
```python ```python
<...> <...>
point = random_point_in_sphere(20.0) point = random_point_in_sphere(20.0)
x = point[0] x = point[0]
y = point[1] y = point[1]
z = point[2] z = point[2]
``` ```
where the variable `point` is a `list` of three `float`s which you can then access with the `[]` syntax. where the variable `point` is a `list` of three `float`s which you can then access with the `[]` syntax.
> The flexibility does have a *cost*, it is *totally up to the programmer* to understand what the function returns and match this up with the variables in the `main()`, failure to do this results in *highly entertaining* bugs! > The flexibility does have a *cost*, it is *totally up to the programmer* to understand what the function returns and match this up with the variables in the `main()`, failure to do this results in *highly entertaining* bugs!
>> **Code Example** >> **Code Example**
- Plot Planck Radiation curve : [Planck Plot](../CodeExamples/PlanckPlot.ipynb) >>- [Plot Planck Radiation curve](../CodeExamples/PlanckPlot.ipynb):
This is a more complicated example with a *function* that returns a >>This is a more complicated example with a *function* that returns a *list*. You will see a >>better way to do this later in the course when we look at the `Map Function`.
*list*. You will see a better way to do this later in the course when we >>- [Volume of Sphere by random numbers](../CodeExamples/SphereVolume.ipynb):
look at the `Map Function`. >>Program to calculate the volume of a sphere by counting three dimensional points; this is an example of a simple Monte Carlo simulation which you will hear more about next year.
- Volume of Sphere by random numbers : [SphereVolume](../CodeExamples/SphereVolume.ipynb)
Program to calculate the volume of a sphere by counting three dimensional points; this is an example of a simple Monte Carlo simulation which you will hear more about next year.
>> Both of these longer examples show how the use of *functions* simplifies >> Both of these longer examples show how the use of *functions* simplifies
the `main()` program and makes it more readable and esier to understand, and hence it is more likely to be correct. the `main()` program and makes it more readable and esier to understand, and hence it is more likely to be correct.
## Functions and Lists ## Functions and Lists
We have seen in that functions basically *do what you expect*, and in We have seen in that functions basically *do what you expect*, and in
particular the variables *inside* the function are separate from those particular the variables *inside* the function are separate from those
in the `main()` program. This is true for the basic build-in types (`str`,`float`, and `int`), but you have to be *very careful* when you pass `list`s into functions. in the `main()` program. This is true for the basic build-in types (`str`,`float`, and `int`), but you have to be *very careful* when you pass `list`s into functions.
Consider what happend in the following code where the function `set_random_list()` sets a given `list` with random numbers. Consider what happend in the following code where the function `set_random_list()` sets a given `list` with random numbers.
```python ```python
def set_random_list(lst): def set_random_list(lst):
""" """
Function to set a list full of random numbers. Function to set a list full of random numbers.
""" """
for i in range(0,len(lst)): for i in range(0,len(lst)):
lst[i] = random.random() lst[i] = random.random()
def main(): def main():
xdata = [0.0]*100 xdata = [0.0]*100
set_random_list(xdata) set_random_list(xdata)
main() main()
``` ```
Now consider what happens, Now consider what happens,
- in the `main()` program we create a list of 100 `float`s, all set to zero, - in the `main()` program we create a list of 100 `float`s, all set to zero,
- then this is passed to the function `set_random_list(xdata)`; the `list` is sent to the function, - then this is passed to the function `set_random_list(xdata)`; the `list` is sent to the function,
- inside the function the data *held* in the `list` is the same as the data in the `main()`, so if you change the values of the elements of the list inside `set_random_list()` then they *will* change in `main()`. - inside the function the data *held* in the `list` is the same as the data in the `main()`, so if you change the values of the elements of the list inside `set_random_list()` then they *will* change in `main()`.
- in `main()`, after the call to `set_random_list(xdata)` the *elements* of the list `xdata` will be set to random numbers. - in `main()`, after the call to `set_random_list(xdata)` the *elements* of the list `xdata` will be set to random numbers.
This operation of functions *is* typically what you want to happen, but This operation of functions *is* typically what you want to happen, but
you have to be very careful that you really intend to modify the you have to be very careful that you really intend to modify the
contents of a list inside the function. contents of a list inside the function.
## Functions and Complex Numbers ## Functions and Complex Numbers
The way that `complex` numbers operate needs a bit of thought on how they work, if you have a `complex` function as below that `returns` a `complex`, The way that `complex` numbers operate needs a bit of thought on how they work, if you have a `complex` function as below that `returns` a `complex`,
```python ```python
def complex_value_compare( a , b): def complex_value_compare( a , b):
if a.real > b.real and a.imag > b.imag: if a.real > b.real and a.imag > b.imag:
return a + b return a + b
else: else:
return a - b return a - b
``` ```
then this will work exactly as you expect and you can *read* the real then this will work exactly as you expect and you can *read* the real
and imaginary parts of the `complex` arguments with the `.real` and `.imag` syntax. *BUT* because of the way the `complex` number is passed you are not able to write to the real and imaginary parts by this route, this means that although a complex number looks like a `list` of two numbers, it cannot be changed inside a function. and imaginary parts of the `complex` arguments with the `.real` and `.imag` syntax. *BUT* because of the way the `complex` number is passed you are not able to write to the real and imaginary parts by this route, this means that although a complex number looks like a `list` of two numbers, it cannot be changed inside a function.
> #### The Tuple > #### The Tuple
There is a variant on the list called a `tuple` which holds multiple elements just like a `list`, is indexed by the same `[i]` syntax for read *but* cannot be written to, so its values are *fixed*. This is not frequently used in normal *user* programs, but is used inside complex libraries to implement constants. There is a variant on the list called a `tuple` which holds multiple elements just like a `list`, is indexed by the same `[i]` syntax for read *but* cannot be written to, so its values are *fixed*. This is not frequently used in normal *user* programs, but is used inside complex libraries to implement constants.
>> You have now completed sufficient to attempt [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb). >> You have now completed sufficient to attempt [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id:54814145 tags:
# Scope of Variables # Scope of Variables
*Scope of variables* means the parts of code where a particular variable *Scope of variables* means the parts of code where a particular variable
is accessible. When you were writing a single program this was simple, is accessible. When you were writing a single program this was simple,
but as you start to use functions and `main()` you need to start to think. but as you start to use functions and `main()` you need to start to think.
## All Local Variables ## All Local Variables
> ### Key Point > ### Key Point
If you define **all** your variables inside functions then the rule is If you define **all** your variables inside functions then the rule is
simple simple
- Variables are local to the function in which they are defined. - Variables are local to the function in which they are defined.
So if we take the example below which forms a list of numbers and then So if we take the example below which forms a list of numbers and then
uses function `add_values()` to sum them up. uses function `add_values()` to sum them up.
```python ```python
def add_values(values): def add_values(values):
x = 0.0 # Local variable x = 0.0 # Local variable
for y in values: #Sum up values in list for y in values: #Sum up values in list
x += y x += y
return x # return local value return x # return local value
def main(): def main():
v = [] # make list of numbers v = [] # make list of numbers
for i in range(0,10): for i in range(0,10):
x = 5.0*i x = 5.0*i
v.append(x) v.append(x)
x = add_values(v) # Sum up with function x = add_values(v) # Sum up with function
print("Sum of values is : " + str(x)) # Print print("Sum of values is : " + str(x)) # Print
main() main()
``` ```
- The `x` used in `add_values()` is local to that function, it is used to hold the sum of the elements of the list and its **value** is returned in line 5 - The `x` used in `add_values()` is local to that function, it is used to hold the sum of the elements of the list and its **value** is returned in line 5
- The `x` used (twice) in `main()` is a *completely separate* to the same named variable in `add_values()`, and in particular it is located in a different location in computer memory, so the value of one does *not* affect the other. - The `x` used (twice) in `main()` is a *completely separate* to the same named variable in `add_values()`, and in particular it is located in a different location in computer memory, so the value of one does *not* affect the other.
> ### Key Point > ### Key Point
Use of local variables is the recommended programming style, it Use of local variables is the recommended programming style, it
- Makes each function separate and removes inter-dependancies - Makes each function separate and removes inter-dependancies
- Allows each function to operate independently of others, so easier - Allows each function to operate independently of others, so easier
to reuse in other applications. to reuse in other applications.
- Easier to test and debug each function seperately. - Easier to test and debug each function seperately.
> **Note: functions have *no memory* from any previous call, so all local variables get re-created every time the function is called.** > **Note: functions have *no memory* from any previous call, so all local variables get re-created every time the function is called.**
## Global Variables ## Global Variables
When variables are declared outside functions, including outside `main()` they become *global*, so When variables are declared outside functions, including outside `main()` they become *global*, so
```python ```python
wave = 6.5 # Declare outside main or fucntion wave = 6.5 # Declare outside main or fucntion
def bright(x): def bright(x):
val = x*wave # Can access global variable wave val = x*wave # Can access global variable wave
return val return val
def main(): def main():
v = bright(15.0) v = bright(15.0)
print("value of bright is : " + str(v) + " and can also access wave " + str(wave)) print("value of bright is : " + str(v) + " and can also access wave " + str(wave))
``` ```
- In Line 1, `wave` is a global float variable declared outside any function. - In Line 1, `wave` is a global float variable declared outside any function.
- In Line 4 and 9 the value of `wave` is accessible. It is also accesible from *any* other function declared within this file. - In Line 4 and 9 the value of `wave` is accessible. It is also accesible from *any* other function declared within this file.
>> Here is a longer example of using a global variable >> Here is a longer example of using a global variable
In this case `wavelength` is visible within both `main()` and the function `planck()`. In this case `wavelength` is visible within both `main()` and the function `planck()`.
> ### Key Point: Rules > ### Key Point: Rules
The rules for global variables are: >The rules for global variables are:
- The global variable must be decared before any function it is used >- The global variable must be decared before any function it is used
in, so typically at the top of the file. in, so typically at the top of the file.
- It is visible from all functions declared within the file. >- It is visible from all functions declared within the file.
- The value of a global **cannot** be changed from within any function >- The value of a global **cannot** be changed from within any function
or `main()`, so it is “*Read Only*”. or `main()`, so it is “*Read Only*”.
> Global variables look *like a good thing*, but they should be used with *extreme care* and only when you want to set a *global default* across a set of functions. > Global variables look *like a good thing*, but they should be used with *extreme care* and only when you want to set a *global default* across a set of functions.
## Changing Globals ## Changing Globals
The default operation of globals is that they are *read only* within The default operation of globals is that they are *read only* within
each function, but you can override this by the use of the `global` keyword as shown below. each function, but you can override this by the use of the `global` keyword as shown below.
```python ```python
wave = 6.5 # Declare outside main or funtion wave = 6.5 # Declare outside main or funtion
def bright(x): def bright(x):
val = x*wave # Can access global variable wave val = x*wave # Can access global variable wave
return val return val
def main(): def main():
global wave # make wave writable fron within main global wave # make wave writable fron within main
v = bright(15.0) v = bright(15.0)
print("value of bright is : " + str(v) + " and can also access wave " + str(wave)) print("value of bright is : " + str(v) + " and can also access wave " + str(wave))
wave = 25.0 # Update global variable wave = 25.0 # Update global variable
v = bright(15.0) v = bright(15.0)
print("value of bright is : " + str(v) + " and can also access wave with new value " + str(wave)) print("value of bright is : " + str(v) + " and can also access wave with new value " + str(wave))
``` ```
So here in line 8 we have declared that `wave` is a writable global in `main()`, so when we update it in line 12 the value seen by function `bright()` also changes. So here in line 8 we have declared that `wave` is a writable global in `main()`, so when we update it in line 12 the value seen by function `bright()` also changes.
> ### Wrong > ### Wrong
Using `global` to make global variables writable within functions is *very dangerous*; it leads to totally unmaintanable code and should only be used when you really understand what you are doing. Using `global` to make global variables writable within functions is *very dangerous*; it leads to totally unmaintanable code and should only be used when you really understand what you are doing.
> WARNING: Having lists in global is a recipe for disaster, there are all sorts of horrible and none obvious consequences; how it works is logical, but typically not what you want; just “don’t do it”. > WARNING: Having lists in global is a recipe for disaster, there are all sorts of horrible and none obvious consequences; how it works is logical, but typically not what you want; just “don’t do it”.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id:0e82b6e6 tags: %% Cell type:markdown id:0e82b6e6 tags:
# Course Assessment # Course Assessment
## Overview ## Overview
The Scientific Programming (SciProg) component of the course Programming and Data Analysis The Scientific Programming (SciProg) component of the course Programming and Data Analysis
is assessed by **6** checkpoints. is assessed by **6** checkpoints.
The checkpoints are assessed on a pass/fail basis only. This is the The checkpoints are assessed on a pass/fail basis only. This is the
basis of “ungrading" philosophy to avoid you being over-assessed and to basis of “ungrading" philosophy to avoid you being over-assessed and to
help you to enjoy learning the skill of programming, rather than worrying help you to enjoy learning the skill of programming, rather than worrying
about marks. Worrying disrupts memory retention. Please enjoy the about marks. Worrying disrupts memory retention. Please enjoy the
course and there are many demonstrators on hand to help. course and there are many demonstrators on hand to help.
You should pass **all** of the checkpoints, but if you fail only one then this one will be discarded. You should pass **all** of the checkpoints, but if you fail only one then this one will be discarded.
Programming is a valuable skill, well-rewarded in employment, and useful for your other courses. Programming is a valuable skill, well-rewarded in employment, and useful for your other courses.
It is also fun and satisfying, while intellectually challenging. Try to learn it well now as it will save you time later. It is also fun and satisfying, while intellectually challenging. Try to learn it well now as it will save you time later.
The Python Programming section is the first part of the Semester 1 course Programming and Data Analysis. The Data Analysis The Python Programming section is the first part of the Semester 1 course Programming and Data Analysis. The Data Analysis
section of the course follows during weeks 8-11 of Semester 1. section of the course follows during weeks 8-11 of Semester 1.
The checkpoints are given below. In practice your deadline will depend upon which day your allocated lab session is. The checkpoints are given below. In practice your deadline will depend upon which day your allocated lab session is.
**There aren't any extensions allowed for this course.** **There aren't any extensions allowed for this course.**
## Checkpoints ## Checkpoints
**Remember before you start a checkpoint please first rename the checkpoint notebook which contains your solutions as CheckpointN_YourUUN, eg. Checkpoint1_s1234567**. **It may be helpful before you start a checkpoint to first rename the checkpoint notebook which contains your solutions as CheckpointN_YourUUN, eg. Checkpoint1_s1234567**.
1. [Checkpoint 1](../Checkpoints/Checkpoint1.ipynb): basic handling of floating point numbers and mathematical 1. [Checkpoint 1](../Checkpoints/Checkpoint1.ipynb): basic handling of floating point numbers and mathematical
functions. functions.
> Deadline: **Thursday 5:00pm 28th September 2023** > Deadline: **Thursday 5:00pm 26th September 2024**
*The first checkpoint has a soft deadline to help with any start-up problems. It must be completed by the end of the course to be taken into account.* *The first checkpoint has a soft deadline to help with any start-up problems. It must be completed by the end of the course to be taken into account.*
2. [Checkpoint 2](../Checkpoints/Checkpoint2.ipynb): to find the root of a quadratic equation. 2. [Checkpoint 2](../Checkpoints/Checkpoint2.ipynb): to find the root of a quadratic equation.
> Deadline: **Thursday 5:00pm 5th October 2023** > Deadline: **Thursday 5:00pm 3rd October 2024**
3. [Checkpoint 3](../Checkpoints/Checkpoint3.ipynb): to plot out a graph of amplitude against time for a damped harmonic 3. [Checkpoint 3](../Checkpoints/Checkpoint3.ipynb): to plot out a graph of amplitude against time for a damped harmonic
oscillator. oscillator.
> Deadline: **Thursday 5:00pm 12th October 2023** > Deadline: **Thursday 5:00pm 10th October 2024**
4. [Checkpoint 4](../Checkpoints/Checkpoint4.ipynb): to read in data from a text file, process the data and plot the 4. [Checkpoint 4](../Checkpoints/Checkpoint4.ipynb): to read in data from a text file, process the data and plot the
output. output.
> Deadline: **Thursday 5:00pm 19th October 2023** > Deadline: **Thursday 5:00pm 17th October 2024**
5. [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb): to calculate path and energy of projectile under drag. 5. [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb): to calculate path and energy of projectile under drag.
> Deadline: **Thursday 5:00pm 26th October 2023** > Deadline: **Thursday 5:00pm 24th October 2024**
6. [Checkpoint 6](../Checkpoints/Checkpoint6.ipynb): to perform a simple Monte Carlo calculation and determine the volume of molecules. 6. [Checkpoint 6](../Checkpoints/Checkpoint6.ipynb): to perform a simple Monte Carlo calculation and determine the volume of molecules.
> Deadline: **Thursday 5.00pm 2rd November 2023** > Deadline: **Thursday 5:00pm 31st October 2024**
## Process ## Process
All checkpoints will be asessed by the demonstrators during the workshop All checkpoints will be asessed by the demonstrators during the workshop
class time. They will: class time. They will:
1. Ask you to run the code with the specified inputs and any with additional 1. Ask you to run the code with the specified inputs and any with additional
inputs they request. inputs they request.
2. Look through your code and ask you questions about specific points 2. Look through your code and ask you questions about specific points
regarding the operation and style of the program. regarding the operation and style of the program.
3. They will assign pass or fail and give you verbal feedback on the style, and 3. They will assign pass or fail and give you verbal feedback on the style, and
where appropriate, how the program could have been improved. where appropriate, how the program could have been improved.
The *minimum* assessment criteria for each checkpoint are specified with the checkpoint description. The *minimum* assessment criteria for each checkpoint are specified with the checkpoint description.
You should strive to have *more* that just a working program. You should strive to have *more* that just a working program.
It should be well organised, have sensible variable names, and suitable comments. It should be well organised, have sensible variable names, and suitable comments.
- At times many people may be trying to have checkpoints done at the same - At times many people may be trying to have checkpoints done at the same
time, so please be patient and work ahead with the material while waiting. time, so please be patient and work ahead with the material while waiting.
- Please ensure that your program works as specified **before** asking to have it checked off. - Please ensure that your program works as specified **before** asking to have it checked off.
%% Cell type:markdown id:13e3c8be tags: %% Cell type:markdown id:13e3c8be tags:
......
%% Cell type:markdown id: tags: %% Cell type:markdown id:e1a67568 tags:
# Basic Functions # Basic Functions
## Main as a function ## Main as a function
Now that you have seen the use of ```functions``` to calculate mathematical expressions Now that you have seen the use of ```functions``` to calculate mathematical expressions
such as ```cos()```, we will see how we can use the same idea to break up your code such as ```cos()```, we will see how we can use the same idea to break up your code
into smaller and manageable sections. into smaller and manageable sections.
The first concept in breaking up your code is to write your program as a ```function```, called ```main()``` as shown below: The first concept in breaking up your code is to write your program as a ```function```, called ```main()``` as shown below:
```python ```python
def main(): def main():
print("Hello world") print("Hello world")
main() main()
``` ```
Here we have Here we have
- **Line 1** declares the start of a ```function``` called ```main()```. *Note: the ":" is a - **Line 1** declares the start of a ```function``` called ```main()```. *Note: the ":" is a
required part of the syntax* required part of the syntax*
- **Line 2** contains the body of the function, here to simply ```print()``` "Hello - **Line 2** contains the body of the function, here to simply ```print()``` "Hello
World", *Note: this must be indented by exactly 4 spaces*. World", *Note: this must be indented by exactly 4 spaces*.
- **Line 4** executes the ```main()``` function, so running the program. - **Line 4** executes the ```main()``` function, so running the program.
### Key Point ### Key Point
As you can see, correct indentation in is *essential* - it As you can see, correct indentation in `Python` is *essential* - it
is part of the syntax of the language. is part of the syntax of the language.
The editor will allow you to use key to do the indentation but you The editor will allow you to use key to do the indentation but you
absolutely *must* get the right every time. There is no margin for absolutely *must* get the right every time. There is no margin for
error! error!
> #### More on indentation > #### More on indentation
In computing languages there are *three* styles to In computing languages there are *three* styles to
designate the start and end of code blocks, these being designate the start and end of code blocks, these being
1. *brackets*, in `C` and `Java` style languages, 1. *brackets*, in `C` and `Java` style languages,
2. *keywords* in `Fortran` and `Shell` scripts. 2. *keywords* in `Fortran` and `Shell` scripts.
3. *indentation* in `Python`. 3. *indentation* in `Python`.
> So in most languages *indentation* of code blocks is *good style* but > So in most languages *indentation* of code blocks is *good style* but
not essential. However (uniquely?) in `Python` the start and end of blocks are not essential. However (uniquely?) in `Python` the start and end of blocks are
designated by *indentation* only; it is part of the syntax of `Python`. This designated by *indentation* only; it is part of the syntax of `Python`. This
makes `Python` code short and concise, but it does mean you *must* get the makes `Python` code short and concise, but it does mean you *must* get the
indentation absolutely right! indentation absolutely right!
Failing to do this is the biggest source of (some very interesting) Failing to do this is the biggest source of (some very interesting)
bugs! bugs!
> Modify your program for Checkpoint1 to use a `main()` function. > Modify your program for Checkpoint1 to use a `main()` function.
## Simple functions ## Simple functions
The power of ```functions``` becomes apparent once we look at functions that can take The power of ```functions``` becomes apparent once we look at functions that can take
*parameters*. Lets consider the code below that uses two functions to *parameters*. Lets consider the code below that uses two functions to
convert temperature values between the centigrade and fahrenheit scale: convert temperature values between the centigrade and fahrenheit scale:
```python ```python
def fahrenheit(t): def fahrenheit(t):
return 1.8*t + 32.0 return 1.8*t + 32.0
def centigrade(t): def centigrade(t):
return (t - 32.0)/1.8 return (t - 32.0)/1.8
def main(): def main():
ct = 100.0 ct = 100.0
ft = fahrenheit(ct) ft = fahrenheit(ct)
print("Temperature of " + str(ct) + " in centigrade is " + str(ft) + " in farenheit") print("Temperature of " + str(ct) + " in centigrade is " + str(ft) + " in farenheit")
ft = 200.0 ft = 200.0
ct = centigrade(ft) ct = centigrade(ft)
print("Temperature of " + str(ft) + " in farenheit is " + str(ct) + " in centigrade") print("Temperature of " + str(ft) + " in farenheit is " + str(ct) + " in centigrade")
main() main()
``` ```
Looking at this in detail, Looking at this in detail,
- **Line 1** declares a function called `fahrenheit()` that takes a value `t` as a - **Line 1** declares a function called `fahrenheit()` that takes a value `t` as a
parameter assumed to be in centigrade. parameter assumed to be in centigrade.
- **Line 2** is the body of the function that takes the value of `t` and calculates the fahrenheit value and `return`s it. - **Line 2** is the body of the function that takes the value of `t` and calculates the fahrenheit value and `return`s it.
- **Line 4-5** defines a function called `centigrade()` that takes a value `t` as a parameter assumed to be in fahrenheit and returns the value in centigrade. - **Line 4-5** defines a function called `centigrade()` that takes a value `t` as a parameter assumed to be in fahrenheit and returns the value in centigrade.
- **Line 9** uses the `fahrenheit()` function. - **Line 9** uses the `fahrenheit()` function.
- **Line 12** uses the `centigrade()` function. - **Line 12** uses the `centigrade()` function.
> Download these two programs and play with them > Have a look at these two programs and play with them:
- Temperature Converter >- [Temperature Converter](../CodeExamples/TemperatureConverter.ipynb)
- Quadratic >- [Quadratic](../CodeExamples/QuadraticFunction.ipynb)
### Key Point ### Key Point
This looks like an unnecessary complication, but as your programs get more complex you will see the benefit. This looks like an unnecessary complication, but as your programs get more complex you will see the benefit.
**You are expected to use this format in all your programs**. In particular **You are expected to use this format in all your programs**. In particular
- Declare `functions` at the top of the code. - Declare `functions` at the top of the code.
- The executed program called `main()` which is defined and then executed by `main()` at the **end** of the file. - The executed program called `main()` which is defined and then executed by `main()` at the **end** of the file.
- **ALL** variables must be declared within `functions()` or `main()` - **ALL** variables must be declared within `functions()` or `main()`
This is *good programming practice* that we want you to learn, it also avoids many of the problems, pitfalls and complications associated with *scope of variables*, details of which are in the optional sections at This is *good programming practice* that we want you to learn, it also avoids many of the problems, pitfalls and complications associated with *scope of variables*, details of which are in the optional sections at
the end of the course. the end of the course.
- [Scope of variables](Scope.ipynb) - [Scope of variables](Scope.ipynb)
You will see how to do more complex operations with functions later, but this will get you started for now. You will see how to do more complex operations with functions later, but this will get you started for now.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id:16d8e959 tags:
# Conditional Statements # Conditional Statements
In order to start making a computer program do more than simple In order to start making a computer program do more than simple
pre-determined calculations we have to introduce the idea of conditional pre-determined calculations we have to introduce the idea of conditional
statements. These make the execution path though the code depend on the statements. These make the execution path though the code depend on the
values of the variables. This is called *Flow Control* and is the first values of the variables. This is called *Flow Control* and is the first
real step in *programming*. real step in *programming*.
> **This section introduces multiple new concepts and syntax, take > **This section introduces multiple new concepts and syntax, take
your time and study it carefully.** your time and study it carefully.**
## The `if-else` structure ## The `if-else` structure
The simplest conditional structure is the `if - else`, to see this consider the The simplest conditional structure is the `if - else`, to see this consider the
section of code below, where `a` is a float variable that has already been section of code below, where `a` is a float variable that has already been
set: set:
```python ```python
<code to set a> <code to set a>
if a > 0 : if a > 0 :
b = 4.0 + math.sqrt(a) b = 4.0 + math.sqrt(a)
a = 2.0*(b + 1.0) a = 2.0*(b + 1.0)
else : else :
b = 4.0 - 3.0*math.sqrt(-a) b = 4.0 - 3.0*math.sqrt(-a)
a = 7.0*(b - 3.0) a = 7.0*(b - 3.0)
print("The value of a is : " + str(a) + " and b is : " + str(b)) print("The value of a is : " + str(a) + " and b is : " + str(b))
``` ```
There is a considerable amount of new syntax here; read through this There is a considerable amount of new syntax here; read through this
very carefully. very carefully.
- Line 1: Sets the value of `a`, which may be positive or negative. - Line 1: Sets the value of `a`, which may be positive or negative.
- Line 2: Start of the `if` with logical statement `a > 0` which will be `True` or `False`. - Line 2: Start of the `if` with logical statement `a > 0` which will be `True` or `False`.
**Note** the `:` which is an essential part of the syntax. **Note** the `:` which is an essential part of the syntax.
- Lines 3 & 4: These two lines are executed only if `a > 0`. - Lines 3 & 4: These two lines are executed only if `a > 0`.
**Note** these lines *must* be indented by exactly 4 spaces. **Note** these lines *must* be indented by exactly 4 spaces.
- Line 5: Start of the `else` code. - Line 5: Start of the `else` code.
**Note** the `:` and also the `else` *must* be aligned with the `if`. **Note** the `:` and also the `else` *must* be aligned with the `if`.
- Lines 6 & 7: These two lines are executed only if `a > 0` is `False`. - Lines 6 & 7: These two lines are executed only if `a > 0` is `False`.
**Note** again they *must* be indented by exactly 4 spaces. **Note** again they *must* be indented by exactly 4 spaces.
- Line 8: Execution continues here *after* the `if: else:` structure. - Line 8: Execution continues here *after* the `if: else:` structure.
**Note** this line *must* be aligned with the `if` and the `else`. **Note** this line *must* be aligned with the `if` and the `else`.
### Key Point ### Key Point
As you can see, correct indentation in `Python` is *essential* - it As you can see, correct indentation in `Python` is *essential* - it
is part of the syntax of the language. is part of the syntax of the language.
The editor will allow you to use `<tab>` key to do the indentation but you The editor will allow you to use `<tab>` key to do the indentation but you
absolutely *must* get the right every time. There is no margin for absolutely *must* get the right every time. There is no margin for
error! error!
> #### More on indentation > #### More on indentation
In computing languages there are *three* styles to >In computing languages there are *three* styles to designate the start and end of code blocks, these being:
designate the start and end of code blocks, these being >1. *brackets*, in C and Java style languages,
1. *brackets*, in C and Java style languages, >2. *keywords* in Fortran and Shell scripts.
2. *keywords* in Fortran and Shell scripts. >3. *indentation* in Python.
3. *indentation* in Python.
> So in most languages *indentation* of code blocks is *good style* but > So in most languages *indentation* of code blocks is *good style* but
not essential. However (uniquely?) in the start and end of blocks are not essential. However (uniquely?) in the start and end of blocks are
designated by *indentation* only; it is part of the syntax of . This designated by *indentation* only; it is part of the syntax of . This
makes code short and concise, but it does mean you *must* get the makes code short and concise, but it does mean you *must* get the
indentation absolutely right! indentation absolutely right!
> Failing to do this is the biggest source of (some very interesting) > Failing to do this is the biggest source of (some very interesting)
bugs! bugs!
The conditional statement, the `a > 0` above, can be any logical statement that you can build up using `and`, `or` and `not`; you will learn more about this later. The conditional statement, the `a > 0` above, can be any logical statement that you can build up using `and`, `or` and `not`; you will learn more about this later.
## The `if-elif-else` structure ## The `if-elif-else` structure
There is a more complete and useful `if-elif-else` construction that you will often use in programming, look at the following example, There is a more complete and useful `if-elif-else` construction that you will often use in programming, look at the following example,
```python ```python
<code to set a> <code to set a>
if a > 4.0 : if a > 4.0 :
b = 4.0 - math.sqrt(a) b = 4.0 - math.sqrt(a)
a = 2.0*(b - 3.0) a = 2.0*(b - 3.0)
elif a > 0 : elif a > 0 :
b = 1.0 + math.sqrt(a) b = 1.0 + math.sqrt(a)
a = (b - 1.0) a = (b - 1.0)
else : else :
b = 4.0 - 3.0*math.sqrt(-a) b = 4.0 - 3.0*math.sqrt(-a)
a = 7.0*(b - 3.0) a = 7.0*(b - 3.0)
print("The value of a is : " +str(a) + " and b is : " + str(b)) print("The value of a is : " +str(a) + " and b is : " + str(b))
``` ```
Looking at this is detail we have: Looking at this is detail we have:
- Line 2: Changes the conditional on line 2 so that lines 3 & 4 will - Line 2: Changes the conditional on line 2 so that lines 3 & 4 will
only be executed if $a > 4$. only be executed if $a > 4$.
- Line 5: Introduces a new statement `elif` (short for *else if*) with an - Line 5: Introduces a new statement `elif` (short for *else if*) with an
additional condition that $a > 0$ and if `True` lines 6 & 7 will be executed. additional condition that $a > 0$ and if `True` lines 6 & 7 will be executed.
- Line 8: The `else` catches *all other cases*, so here Lines 8 & 9 will be - Line 8: The `else` catches *all other cases*, so here Lines 8 & 9 will be
executed when $a \leq 0$. executed when $a \leq 0$.
### Key Point ### Key Point
Here it is essential to note that: Here it is essential to note that:
- only **one** of the indented blocks of code will be executed, and - only **one** of the indented blocks of code will be executed, and
- this will be determined at the execution of the initial `if` statement. - this will be determined at the execution of the initial `if` statement.
This looks a more complex piece of code but it will become one of the This looks a more complex piece of code but it will become one of the
most common constructs you will use in programs. most common constructs you will use in programs.
## Nested if : else ## Nested if : else
You can nest `if: elif: else:` blocks to any depth you like, so for example you can have: You can nest `if: elif: else:` blocks to any depth you like, so for example you can have:
```python ```python
<code to set a> <code to set a>
<code to set b> <code to set b>
if a > 0: if a > 0:
if b > 0 : if b > 0 :
val = math.sqrt(b/a) val = math.sqrt(b/a)
else: val = math.sqrt(-b/a) else: val = math.sqrt(-b/a)
else: else:
if b > -10 : if b > -10 :
val = math.sqrt(-a / (b + 11.0)) val = math.sqrt(-a / (b + 11.0))
else: val = float("nan") else: val = float("nan")
print("Val is : " +str(val)) print("Val is : " +str(val))
``` ```
Here: Here:
- Line 3: Tests on variable `a`. The execution thread will jump *either* - Line 3: Tests on variable `a`. The execution thread will jump *either*
to Line 4 *or* to Line 9. to Line 4 *or* to Line 9.
- Lines 4 to 7: Will be executed only if the test on Line 3 is `True`. - Lines 4 to 7: Will be executed only if the test on Line 3 is `True`.
Either Line 5 or Line 7 will be executed depending on the test on Either Line 5 or Line 7 will be executed depending on the test on
Line 4. Line 4.
- Lines 9 to 12: Will be executed only if the test on Line 3 is `False`. - Lines 9 to 12: Will be executed only if the test on Line 3 is `False`.
Either Line 10 or Line 12 will be executed depending on the test on Either Line 10 or Line 12 will be executed depending on the test on
Line 9. Line 9.
- Line 13: Will print out the final value of `val` . - Line 13: Will print out the final value of `val` .
Note here the indentation; Lines 4, 6, 9 and 11 *must* be indented by 4 Note here the indentation; Lines 4, 6, 9 and 11 *must* be indented by 4
spaces while lines 5, 7, 10 and 12 *must* be indented by 8 spaces. spaces while lines 5, 7, 10 and 12 *must* be indented by 8 spaces.
### Key Point ### Key Point
You can nest `if: elif: else:` to any *depth*, **but** such complex structure are You can nest `if: elif: else:` to any *depth*, **but** such complex structure are
difficult to write and even more difficult to debug. difficult to write and even more difficult to debug.
The general rule is: The general rule is:
- Do not nest deeper than two levels - if you find you have to, - Do not nest deeper than two levels - if you find you have to,
consider using *functions* to break up the code (see later in consider using *functions* to break up the code (see later in
course). course).
- Add careful comments explaining what you are doing. - Add careful comments explaining what you are doing.
>**Example Code:** >**Example Code:**
- One way example: >- [One way example](../CodeExamples/OneWayConditional.ipynb)
- Two way example: >- [Two way example](../CodeExamples/TwoWayConditional.ipynb)
- Three way example: >- [Three way example](../CodeExamples/ThreeWayConditional.ipynb)
- Which quadrant is a complex number in : >- [Which quadrant is a complex number in](../CodeExamples/ComplexQuadrant.ipynb)
- Is point inside sphere using a function : >- [Is point inside circle using a function](../CodeExamples/PointsInCircle.ipynb)
> Download these and "play" with them; in particular change in indentation > Download these and "play" with them; in particular change in indentation
and see what type of "crashes" you get. and see what type of "crashes" you get.
>> Once you have practiced and understood the `if : elif: else:` syntax you have completed >> Once you have practiced and understood the `if : elif: else:` syntax you have completed
enough to attempt [Checkpoint 2](../Checkpoints/Checkpoint2.ipynb) enough to attempt [Checkpoint 2](../Checkpoints/Checkpoint2.ipynb)
Note, Checkpoint is much more tricky than it looks, read in instuctions Note, Checkpoint 2 is much more tricky than it looks, read in instructions
and the **Hint** and plan out all the conditions that your program has and the **Hint** and plan out all the conditions that your program has
to deal with. to deal with.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id:a3ba9097 tags: %% Cell type:markdown id:a3ba9097 tags:
# File Input and Output # File Input and Output
In `Terminal Input and Output`, you learned how to read and write to the terminal window, but to deal with larger amounts of data we need to be able to read and write from and to files. In `Terminal Input and Output`, you learned how to read and write to the terminal window, but to deal with larger amounts of data we need to be able to read and write from and to files.
Here we will only consider text files, which are the same type of files Here we will only consider text files, which are the same type of files
created by the editor and used to hold your `Python` source code. created by the editor and used to hold your `Python` source code.
## Opening files to Write ## Opening files to Write
Before writing to a file you must first open it which is done with: Before writing to a file you must first open it which is done with:
```python ```python
fileout = open("mydata.dat","w") fileout = open("mydata.dat","w")
``` ```
- this will open a file called `mydata.dat` in your current directory with access code of `"w"` for *write* access. - this will open a file called `mydata.dat` in your current directory with access code of `"w"` for *write* access.
- it will return a *filestream* in the variable `fileout`, which you will use to access the file. You do not need to concern youself with the details of what a *filestream* is at this point in your programming career; just use it. - it will return a *filestream* in the variable `fileout`, which you will use to access the file. You do not need to concern youself with the details of what a *filestream* is at this point in your programming career; just use it.
- if the file `mydata.dat` already exists it will be *overwritten*, see more advanced use below to change this. - if the file `mydata.dat` already exists it will be *overwritten*, see more advanced use below to change this.
You can now write `str` to this file *line-by-line* with for example, You can now write `str` to this file *line-by-line* with for example,
```python ```python
x = 3.456e-6 x = 3.456e-6
fileout.write("The value of x is : " + str(x) + "\n") fileout.write("The value of x is : " + str(x) + "\n")
``` ```
which will form a single string and then write it to the opened file. which will form a single string and then write it to the opened file.
This has basic syntax as the `print()` that you used to write to the terminal, *except* This has basic syntax as the `print()` that you used to write to the terminal, *except*
- the extra `"\n"` at the end which adds a *newline* character to the end of the written `str` - the extra `"\n"` at the end which adds a *newline* character to the end of the written `str`
You can then simply repeat this `.write()` for as many other lines as you wish to write. You can then simply repeat this `.write()` for as many other lines as you wish to write.
> #### Why the extra newline > #### Why the extra newline
The default `print()` command automatically adds the `"\n"`*behind-the-scenes* since it is *usually what you want*. This is sensible for output to a terminal, but for file output you want more control. The default `.write()` does only a write of the raw string that you supply, so you have to add the `"\n"` yourself. The default `print()` command automatically adds the `"\n"`*behind-the-scenes* since it is *usually what you want*. This is sensible for output to a terminal, but for file output you want more control. The default `.write()` does only a write of the raw string that you supply, so you have to add the `"\n"` yourself.
> This is the common convention in all similar languages, for example `C` and `Java`. > This is the common convention in all similar languages, for example `C` and `Java`.
### Key Point ### Key Point
So the easiest way to output to a file is: So the easiest way to output to a file is:
1. open the file with `open(filename, "w")` 1. open the file with `open(filename, "w")`
2. for each line convert to a string using `str()` and append a newline 2. for each line convert to a string using `str()` and append a newline
character using ` + "\n"` character using ` + "\n"`
3. write the string to the *filestream* using `.write()` 3. write the string to the *filestream* using `.write()`
This is sufficient to get you started and for many scientific `Python` programs that deal with small amounts of data this is the only strategy you will *ever need to use*. This is sufficient to get you started and for many scientific `Python` programs that deal with small amounts of data this is the only strategy you will *ever need to use*.
> **Code Examples** > **Code Examples**
- Write strings to a file: [WriteFile](../CodeExamples/WriteFile.ipynb) >- Write strings to a file: [WriteFile](../CodeExamples/WriteFile.ipynb)
- Write values to a file from a for loop: [RangeLooptoFile](../CodeExamples/RangeLooptoFile.ipynb) >- Write values to a file from a for loop: [RangeLooptoFile](../CodeExamples/RangeLooptoFile.ipynb)
> Download and "play". > Have a look around and "play".
## Opening files to Read ## Opening files to Read
Reading from a file is basically the reverse of write, so firstly we Reading from a file is basically the reverse of write, so firstly we
open the file, for example open the file, for example
```python ```python
filein = open("mydata.dat","r") filein = open("mydata.dat","r")
``` ```
1. will open a file called `mydata.dat` in your current directory for access key `"r"` (read access), 1. will open a file called `mydata.dat` in your current directory for access key `"r"` (read access),
2. it will return the *filestream* in the variable `filein` which you will use to read from, 2. it will return the *filestream* in the variable `filein` which you will use to read from,
3. if the file `mydata.dat` does not exist you program *will* crash; you will learn how to trap this in later courses. 3. if the file `mydata.dat` does not exist you program *will* crash; you will learn how to trap this in later courses.
You would not normally *hard code* the filename into your program but You would not normally *hard code* the filename into your program but
ask for it as shown in `Printing and reading to/from the Terminal`, so your code would be: ask for it as shown in `Printing and reading to/from the Terminal`, so your code would be:
```python ```python
filename = input("File to open : ") filename = input("File to open : ")
filein = open(filename, "r") filein = open(filename, "r")
``` ```
which will ask you for the filename, and then open it. which will ask you for the filename, and then open it.
Once you have the opened the file you can *read* from it. There are Once you have the opened the file you can *read* from it. There are
*many* strategies for reading from files, but the simplest is using: *many* strategies for reading from files, but the simplest is using:
```python ```python
lines = filein.readlines() lines = filein.readlines()
``` ```
which will read in the *whole* file and return each line and as the which will read in the *whole* file and return each line and as the
elements of a list of strings, so that elements of a list of strings, so that
1. `lines[0]` is a string containing the first line of the file, 1. `lines[0]` is a string containing the first line of the file,
2. `lines[1]` is a string containing the second line of the file, 2. `lines[1]` is a string containing the second line of the file,
3. `len(lines)` is the number of lines successfully read. 3. `len(lines)` is the number of lines successfully read.
How you now process this list of strings is the trickier bit, see next How you now process this list of strings is the trickier bit, see next
section for details on this at [Parsing Input](ParsingInput.ipynb). section for details on this at [Parsing Input](ParsingInput.ipynb).
## Closing the file ## Closing the file
When you have written or read the contents of a file you can close it When you have written or read the contents of a file you can close it
with with
```python ```python
filein.close() filein.close()
``` ```
where `filein` is the *filestream*. This will close the file and tidy up. When a program exits successfully or *crashes* all open files are automatically *closed* so this is not something you have worry about in short programs, but it is *good programming style* to close files after the read/write has been completed. where `filein` is the *filestream*. This will close the file and tidy up. When a program exits successfully or *crashes* all open files are automatically *closed* so this is not something you have worry about in short programs, but it is *good programming style* to close files after the read/write has been completed.
> **Code Examples** > **Code Examples**
- Read text file as strings: [ReadingandPrintingStrings](../CodeExamples/ReadingandPrintingStrings.ipynb) >- Read text file as strings: [ReadingandPrintingStrings](../CodeExamples/ReadingandPrintingStrings.ipynb)
> Download and "play". > Have a look around and "play".
### Other types of files ### Other types of files
There many other types of files that hold *binary* data, for example There many other types of files that hold *binary* data, for example
sound files, images (jpeg, png) , movies (mov, mp4), spreadsheets (xls, sound files, images (jpeg, png) , movies (mov, mp4), spreadsheets (xls,
xlsx) etc. These types cannot just processed as above and are much more xlsx) etc. These types cannot just processed as above and are much more
complex. complex.
These are almost always read/written via library calls so the `Python` programmer does not need to know their internal structure; so for These are almost always read/written via library calls so the `Python` programmer does not need to know their internal structure; so for
example if you want to know how to read a `jpeg` image file, search (or Google) for the right module and the right call and use it, *“do not re-invent the wheel…”*. example if you want to know how to read a `jpeg` image file, search (or Google) for the right module and the right call and use it, *“do not re-invent the wheel…”*.
For example you can read and display a `jpeg` image using Matlibplot with: For example you can read and display a `jpeg` image using Matlibplot with:
```python ```python
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib.image as img # Import image module import matplotlib.image as img # Import image module
image = img.imread("myimage.jpeg") # Read the jpeg image = img.imread("myimage.jpeg") # Read the jpeg
plt.imshow(image) #render it in plot axis plt.imshow(image) #render it in plot axis
plt.show() # display it plt.show() # display it
``` ```
which does a default read and display without needing to know about the which does a default read and display without needing to know about the
internal complexities of `jpeg` images. internal complexities of `jpeg` images.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Loops and Looping # Loops and Looping
To get into real programming we have to look at loops; here we have a 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). *block* of code that is repeated either a set number of times (`for` loops) *or* until some condition is reached (`while` loops).
#### Key Point #### Key Point
The use of *loops* can often be a significant hurdle for new The use of *loops* can often be a significant hurdle for new
programmers but it is absolutely key to programming. Any “non-trivial” programmers but it is absolutely key to programming. Any “non-trivial”
program contains loops, often many of them, and is the key to a 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 computer’s main strength of “doing the same simple thing over and over
again…” very fast. again…” very fast.
## Fixed length loops ## Fixed length loops
First we will start with the simplest case of fixed length loops. Assume 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 we want to print out values of $\cos(\theta)$ in the range
$0\rightarrow2\pi$ using a `for` loop. Consider the piece of code: $0\rightarrow2\pi$ using a `for` loop. Consider the piece of code:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import math import math
points = 50 points = 50
dt = 2.0*math.pi/points dt = 2.0*math.pi/points
for i in range(0,points): for i in range(0,points):
theta = dt*i theta = dt*i
value = math.cos(theta) value = math.cos(theta)
print("theta is : " + str(theta) + " cos(theta) : " + str(value)) print("theta is : " + str(theta) + " cos(theta) : " + str(value))
print("End of loop") print("End of loop")
``` ```
%% Output %% Output
theta is : 0.0 cos(theta) : 1.0 theta is : 0.0 cos(theta) : 1.0
theta is : 0.12566370614359174 cos(theta) : 0.9921147013144779 theta is : 0.12566370614359174 cos(theta) : 0.9921147013144779
theta is : 0.25132741228718347 cos(theta) : 0.9685831611286311 theta is : 0.25132741228718347 cos(theta) : 0.9685831611286311
theta is : 0.3769911184307752 cos(theta) : 0.9297764858882513 theta is : 0.3769911184307752 cos(theta) : 0.9297764858882513
theta is : 0.5026548245743669 cos(theta) : 0.8763066800438636 theta is : 0.5026548245743669 cos(theta) : 0.8763066800438636
theta is : 0.6283185307179586 cos(theta) : 0.8090169943749475 theta is : 0.6283185307179586 cos(theta) : 0.8090169943749475
theta is : 0.7539822368615504 cos(theta) : 0.7289686274214116 theta is : 0.7539822368615504 cos(theta) : 0.7289686274214116
theta is : 0.8796459430051422 cos(theta) : 0.6374239897486896 theta is : 0.8796459430051422 cos(theta) : 0.6374239897486896
theta is : 1.0053096491487339 cos(theta) : 0.5358267949789965 theta is : 1.0053096491487339 cos(theta) : 0.5358267949789965
theta is : 1.1309733552923256 cos(theta) : 0.42577929156507266 theta is : 1.1309733552923256 cos(theta) : 0.42577929156507266
theta is : 1.2566370614359172 cos(theta) : 0.30901699437494745 theta is : 1.2566370614359172 cos(theta) : 0.30901699437494745
theta is : 1.3823007675795091 cos(theta) : 0.18738131458572452 theta is : 1.3823007675795091 cos(theta) : 0.18738131458572452
theta is : 1.5079644737231008 cos(theta) : 0.0627905195293133 theta is : 1.5079644737231008 cos(theta) : 0.0627905195293133
theta is : 1.6336281798666925 cos(theta) : -0.0627905195293134 theta is : 1.6336281798666925 cos(theta) : -0.0627905195293134
theta is : 1.7592918860102844 cos(theta) : -0.18738131458572482 theta is : 1.7592918860102844 cos(theta) : -0.18738131458572482
theta is : 1.884955592153876 cos(theta) : -0.30901699437494756 theta is : 1.884955592153876 cos(theta) : -0.30901699437494756
theta is : 2.0106192982974678 cos(theta) : -0.4257792915650727 theta is : 2.0106192982974678 cos(theta) : -0.4257792915650727
theta is : 2.1362830044410597 cos(theta) : -0.5358267949789969 theta is : 2.1362830044410597 cos(theta) : -0.5358267949789969
theta is : 2.261946710584651 cos(theta) : -0.6374239897486897 theta is : 2.261946710584651 cos(theta) : -0.6374239897486897
theta is : 2.387610416728243 cos(theta) : -0.7289686274214117 theta is : 2.387610416728243 cos(theta) : -0.7289686274214117
theta is : 2.5132741228718345 cos(theta) : -0.8090169943749473 theta is : 2.5132741228718345 cos(theta) : -0.8090169943749473
theta is : 2.6389378290154264 cos(theta) : -0.8763066800438636 theta is : 2.6389378290154264 cos(theta) : -0.8763066800438636
theta is : 2.7646015351590183 cos(theta) : -0.9297764858882515 theta is : 2.7646015351590183 cos(theta) : -0.9297764858882515
theta is : 2.8902652413026098 cos(theta) : -0.9685831611286311 theta is : 2.8902652413026098 cos(theta) : -0.9685831611286311
theta is : 3.0159289474462017 cos(theta) : -0.9921147013144779 theta is : 3.0159289474462017 cos(theta) : -0.9921147013144779
theta is : 3.1415926535897936 cos(theta) : -1.0 theta is : 3.1415926535897936 cos(theta) : -1.0
theta is : 3.267256359733385 cos(theta) : -0.9921147013144779 theta is : 3.267256359733385 cos(theta) : -0.9921147013144779
theta is : 3.392920065876977 cos(theta) : -0.9685831611286311 theta is : 3.392920065876977 cos(theta) : -0.9685831611286311
theta is : 3.518583772020569 cos(theta) : -0.9297764858882512 theta is : 3.518583772020569 cos(theta) : -0.9297764858882512
theta is : 3.6442474781641603 cos(theta) : -0.8763066800438635 theta is : 3.6442474781641603 cos(theta) : -0.8763066800438635
theta is : 3.769911184307752 cos(theta) : -0.8090169943749472 theta is : 3.769911184307752 cos(theta) : -0.8090169943749472
theta is : 3.8955748904513436 cos(theta) : -0.7289686274214116 theta is : 3.8955748904513436 cos(theta) : -0.7289686274214116
theta is : 4.0212385965949355 cos(theta) : -0.6374239897486895 theta is : 4.0212385965949355 cos(theta) : -0.6374239897486895
theta is : 4.1469023027385274 cos(theta) : -0.5358267949789963 theta is : 4.1469023027385274 cos(theta) : -0.5358267949789963
theta is : 4.272566008882119 cos(theta) : -0.42577929156507216 theta is : 4.272566008882119 cos(theta) : -0.42577929156507216
theta is : 4.39822971502571 cos(theta) : -0.30901699437494756 theta is : 4.39822971502571 cos(theta) : -0.30901699437494756
theta is : 4.523893421169302 cos(theta) : -0.18738131458572463 theta is : 4.523893421169302 cos(theta) : -0.18738131458572463
theta is : 4.649557127312894 cos(theta) : -0.06279051952931321 theta is : 4.649557127312894 cos(theta) : -0.06279051952931321
theta is : 4.775220833456486 cos(theta) : 0.06279051952931372 theta is : 4.775220833456486 cos(theta) : 0.06279051952931372
theta is : 4.900884539600078 cos(theta) : 0.18738131458572513 theta is : 4.900884539600078 cos(theta) : 0.18738131458572513
theta is : 5.026548245743669 cos(theta) : 0.30901699437494723 theta is : 5.026548245743669 cos(theta) : 0.30901699437494723
theta is : 5.152211951887261 cos(theta) : 0.4257792915650726 theta is : 5.152211951887261 cos(theta) : 0.4257792915650726
theta is : 5.277875658030853 cos(theta) : 0.5358267949789968 theta is : 5.277875658030853 cos(theta) : 0.5358267949789968
theta is : 5.403539364174445 cos(theta) : 0.63742398974869 theta is : 5.403539364174445 cos(theta) : 0.63742398974869
theta is : 5.529203070318037 cos(theta) : 0.7289686274214119 theta is : 5.529203070318037 cos(theta) : 0.7289686274214119
theta is : 5.6548667764616285 cos(theta) : 0.8090169943749478 theta is : 5.6548667764616285 cos(theta) : 0.8090169943749478
theta is : 5.7805304826052195 cos(theta) : 0.8763066800438636 theta is : 5.7805304826052195 cos(theta) : 0.8763066800438636
theta is : 5.906194188748811 cos(theta) : 0.9297764858882515 theta is : 5.906194188748811 cos(theta) : 0.9297764858882515
theta is : 6.031857894892403 cos(theta) : 0.9685831611286312 theta is : 6.031857894892403 cos(theta) : 0.9685831611286312
theta is : 6.157521601035995 cos(theta) : 0.9921147013144779 theta is : 6.157521601035995 cos(theta) : 0.9921147013144779
End of loop End of loop
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Looking at this in detail: 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 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 - Line 2: is the separation between each value of $\theta$ we wish to
calculate. 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: - 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. - It will *stop* before 50, so at 49.
- The `:` at the end of the line is essential and is part of the - The `:` at the end of the line is essential and is part of the
syntax. syntax.
> #### Range function > #### Range function
The range function has the full syntax The range function has the full syntax
```python ```python
range(start,end,step) 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. 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* > All arguments *must* be `int`, and the loop will terminate *before*
reaching the `end` value. reaching the `end` value.
- Line 4 to 6: the indented code is *inside* the loop: - Line 4 to 6: the indented code is *inside* the loop:
- Calculate $\theta$ by scaling `i` where `dt` is the separation between values. - Calculate $\theta$ by scaling `i` where `dt` is the separation between values.
- Calculate `value`, being $\cos(\theta)$. - Calculate `value`, being $\cos(\theta)$.
- Print out the value of $\theta$ and of $\cos(\theta)$ to the - Print out the value of $\theta$ and of $\cos(\theta)$ to the
screen. screen.
It will do this 50 times. It will do this 50 times.
- Line 7: Print `End of Loop` when the loop is finished; it will only print this - Line 7: Print `End of Loop` when the loop is finished; it will only print this
once. once.
### Key Point ### Key Point
Note the most important bits of syntax here are Note the most important bits of syntax here are
- that the body of the loop, (lines 4,5, & 6), *must* be indented by - that the body of the loop, (lines 4,5, & 6), *must* be indented by
*exactly 4 spaces*. *exactly 4 spaces*.
- the loop variable `int` in that is automatically incremented each time round the loop. - 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 - 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 start (even if the loop variable in changed within the body of the
loop). loop).
## Loop access of lists ## Loop access of lists
One of the main applications of loops is to access the elements of a 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. 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 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: %% Cell type:code id: tags:
``` python ``` python
total = 0.0 total = 0.0
for i in range(0,len(mydata)): for i in range(0,len(mydata)):
total = total + mydata[i]**2 total = total + mydata[i]**2
print("The total of mydata squared is : " + str(total)) print("The total of mydata squared is : " + str(total))
``` ```
%% Output %% Output
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
NameError Traceback (most recent call last) NameError Traceback (most recent call last)
<ipython-input-2-3cb76652cfbb> in <module> <ipython-input-2-3cb76652cfbb> in <module>
1 total = 0.0 1 total = 0.0
----> 2 for i in range(0,len(mydata)): ----> 2 for i in range(0,len(mydata)):
3 total = total + mydata[i]**2 3 total = total + mydata[i]**2
4 4
5 print("The total of mydata squared is : " + str(total)) 5 print("The total of mydata squared is : " + str(total))
NameError: name 'mydata' is not defined NameError: name 'mydata' is not defined
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
which in detail does the following: which in detail does the following:
- Line 1: create a variable `total` and set its initial value to zero. - 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 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 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. - Line 5: at the end of the loop print out the answer.
> #### Missing Line 4 > #### 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. 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. > 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 ### Key Point
Here again the key points of this loop are Here again the key points of this loop are
- the number of times the loop is executed is determined as the start, - the number of times the loop is executed is determined as the start,
it is `len(mydata)`. it is `len(mydata)`.
- the loop index `i` is automatically incremented by $+1$ every time round the loop. - 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. - 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 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 is a more compact syntax to do the same thing; take the following piece
of code. of code.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
total = 0.0 total = 0.0
for d in mydata: for d in mydata:
total = total + d*d total = total + d*d
print("The total of mydata squared is : " + str(total)) print("The total of mydata squared is : " + str(total))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- Line 1: create variable `total` and set it to zero. - 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 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 3: add the value of `d` squared to `total`.
- Line 5: at the end of the loop, print out the final value. - 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 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. shorter, more computationally efficient and in `Python` style, but somewhat more difficult to understand.
> #### Being Pythonic > #### Being Pythonic
Being “Pythonic” is a statement you will find all over Being “Pythonic” is a statement you will find all over
the web; it means doing something in “python style” which usually means 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. 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 > You will find must heated *debate* about this on the computing forums
often by people who’s knowledge is questionable, but you should often by people who’s knowledge is questionable, but you should
concentrate on getting your programs to work and understand what they concentrate on getting your programs to work and understand what they
are doing first. Worry about making them “Pythonic” as you gain are doing first. Worry about making them “Pythonic” as you gain
experience. Do NOT copy down “magic recipes” from forums that you don’t experience. Do NOT copy down “magic recipes” from forums that you don’t
understand and may not do what you want / expect. understand and may not do what you want / expect.
## The `while` loop ## The `while` loop
The other looping construct is when at the start of the loop we **do not 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 know** how many times the loop is to be executed, for example consider
the code below: the code below:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
x = 0 x = 0
while x < 100 : while x < 100 :
x = x + random.randint(1,6) x = x + random.randint(1,6)
print("Final value of x is : " + str(x)) print("Final value of x is : " + str(x))
``` ```
%% Output %% Output
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
NameError Traceback (most recent call last) NameError Traceback (most recent call last)
<ipython-input-4-cbfe5d858a1f> in <module> <ipython-input-4-cbfe5d858a1f> in <module>
1 x = 0 1 x = 0
2 while x < 100 : 2 while x < 100 :
----> 3 x = x + random.randint(1,6) ----> 3 x = x + random.randint(1,6)
4 4
5 print("Final value of x is : " + str(x)) 5 print("Final value of x is : " + str(x))
NameError: name 'random' is not defined NameError: name 'random' is not defined
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
so looking at this in detail, so looking at this in detail,
- Line 1: set the initial value of `x` - 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` - 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 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 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. 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 This type of loop is the key to solving Checkpont 5 in a couple of
weeks. weeks.
> #### Getting stuck > #### Getting stuck
The “danger” of the `while` loops is forgetting to update the The “danger” of the `while` loops is forgetting to update the
variable that control the termination condition. The loop then never variable that control the termination condition. The loop then never
terminates and the program “hangs” going round-and-round “for ever”. If terminates and the program “hangs” going round-and-round “for ever”. If
(when) this happens (when) this happens
- Type `Cntl-C` (both keys at once) which will interrupt the program and tell you where it was in the code. - 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 - If you can’t see the problem, print out the termination variable in
the loop to see what is happening. the loop to see what is happening.
## The `break` statement ## The `break` statement
An important concept associated with loops is the ability to “break out An important concept associated with loops is the ability to “break out
off a loop early”, which overrides the normal loop termination off a loop early”, which overrides the normal loop termination
condition, so for example we could have: condition, so for example we could have:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
total = 0 total = 0
while total < 100 : while total < 100 :
x = <function that sets x> x = <function that sets x>
if x < 0 : if x < 0 :
break break
else : else :
total = total + x total = total + x
print("End of loop") print("End of loop")
``` ```
%% Output %% Output
File "<ipython-input-6-cb0d11525ce0>", line 3 File "<ipython-input-6-cb0d11525ce0>", line 3
x = <function that sets x> x = <function that sets x>
^ ^
SyntaxError: invalid syntax SyntaxError: invalid syntax
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
so in detail so in detail
- Line 1: set `total` to zero - Line 1: set `total` to zero
- Line 2: start of `while` loop, which should run until $total < 100$ - Line 2: start of `while` loop, which should run until $total < 100$
- Line 3: code that calculates a value for `x` - 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 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. - 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. 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 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: infinite loop and then use the `break` statement as the exit, for example:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
while True : while True :
x = \<function to set x> x = \<function to set x>
if x > 100: if x > 100:
break break
print("End of loop") print("End of loop")
``` ```
%% Cell type:markdown id:8dd67a17 tags: %% Cell type:markdown id:8dd67a17 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). 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 This is a construct that is often used in interactive programs that keep
taking “command” for example keeps asking for files to process or taking “command” for example keeps asking for files to process or
programs with a “graphical user interface” (GUI), but should be used programs with a “graphical user interface” (GUI), but should be used
with care in general programming since it difficult to debug and work with care in general programming since it difficult to debug and work
out what is really happening. out what is really happening.
> **Code Examples** > **Code Examples**
- Loop to terminal using for range : [RangeLoop](../CodeExamples/RangeLoop.ipynb) >- Loop to terminal using for range : [RangeLoop](../CodeExamples/RangeLoop.ipynb)
- Loop to list using for range : [RangeLooptoList](../CodeExamples/RangeLooptoList.ipynb) >- Loop to list using for range : [RangeLooptoList](../CodeExamples/RangeLooptoList.ipynb)
- Loop to list using while : [WhileLooptoList](../CodeExamples/WhileLooptoList.ipynb) >- Loop to list using while : [WhileLooptoList](../CodeExamples/WhileLooptoList.ipynb)
- Guessing Game using `while` and `break`: [GuessGame](../CodeExamples/GuessGame.ipynb) >- Guessing Game using `while` and `break`: [GuessGame](../CodeExamples/GuessGame.ipynb)
> You should have a look at these examples and "play" with them. > You should have a look at these examples and "play" with them.
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Simple Graphs # Simple Graphs
There are no graphics in standard `Python`; they have to be added by using an additional module. The standard package used in scientific computing is `MatPlotLib` which is an extensive data presentation package that produces two and three dimensional data plots, displays images, and supports animation; so all the graphics that most people will ever need. We will start of with the simplest use of this package to produce simple graphs and histograms. There are no graphics in standard `Python`; they have to be added by using an additional module. The standard package used in scientific computing is `MatPlotLib` which is an extensive data presentation package that produces two and three dimensional data plots, displays images, and supports animation; so all the graphics that most people will ever need. We will start of with the simplest use of this package to produce simple graphs and histograms.
## Getting Started ## Getting Started
### Key Point ### Key Point
You must first import the library, so at the top of your program put the line You must first import the library, so at the top of your program put the line
```python ```python
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
``` ```
What this does is: What this does is:
- imports `pyplot` components from module `matplotlib` - imports `pyplot` components from module `matplotlib`
- and calls it `plt` - and calls it `plt`
This is what you need for simple plots. See the examples below for what this means in practice. This is what you need for simple plots. See the examples below for what this means in practice.
Now if you have X and Y data in two lists of `float`s (see Section 11) called `xdata` and `ydata`, then you can plot this as a simple x/y graph (the default graph) Now if you have X and Y data in two lists of `float`s (see Section 11) called `xdata` and `ydata`, then you can plot this as a simple x/y graph (the default graph)
```python ```python
plt.plot( xdata, ydata) plt.plot( xdata, ydata)
plt.show() plt.show()
``` ```
Note the syntax: Note the syntax:
- Line 1: the name of the `plot` function is `plt.plot()`, you specified the `plt` prefix on the import, this function builds the graph, taking the two lists as the arguments. - Line 1: the name of the `plot` function is `plt.plot()`, you specified the `plt` prefix on the import, this function builds the graph, taking the two lists as the arguments.
- Line 2: `plt.show()` displays the graph on your screen. How it does this depends on the exact details of what system you are using (see below for more details). - Line 2: `plt.show()` displays the graph on your screen. How it does this depends on the exact details of what system you are using (see below for more details).
> #### The plt name > #### The plt name
Importing the `matplotlib.pyplot` as `plt` shortens the call since without this the the full call would be Importing the `matplotlib.pyplot` as `plt` shortens the call since without this the the full call would be
```python ```python
matplotlib.pyplot.plot(xdata , ydata) matplotlib.pyplot.plot(xdata , ydata)
``` ```
which is getting rather verbose. You can perform this type of import with any library, so for example you can import `math` with which is getting rather verbose. You can perform this type of import with any library, so for example you can import `math` with
```python ```python
import math as m import math as m
``` ```
then the mathematical functions call become `m.cos()`, `m.sin()` etc. then the mathematical functions call become `m.cos()`, `m.sin()` etc.
## Where the plot goes ## Where the plot goes
How the plot appears on your screen depends on how your environment is set up: How the plot appears on your screen depends on how your environment is set up:
### Using Jupyter ### Using Jupyter
Using `Jupyter` the plot will automatically appear within the browser below the cell that you are executing from. Using `Jupyter` the plot will automatically appear within the browser below the cell that you are executing from.
### Using Spyder ### Using Spyder
Using the `Spyder` IDE the default is for the plot to appear in-line in the iPython console window where you type commands, this is OK for checking code, but it does not allow you to zoom / pan the graph. To allow this: Using the `Spyder` IDE the default is for the plot to appear in-line in the iPython console window where you type commands, this is OK for checking code, but it does not allow you to zoom / pan the graph. To allow this:
1. Open `Preferences` from the `Python` menu, this will open a large `Preference` panel with many options. 1. Open `Preferences` from the `Python` menu, this will open a large `Preference` panel with many options.
2. Select `iPython` console, which will open a panel with set of Tabs on the top. 2. Select `iPython` console, which will open a panel with set of Tabs on the top.
3. Select `Graphics`, which will open a panel with many options. 3. Select `Graphics`, which will open a panel with many options.
4. In the panel `Graphics backend` there is option tab labelled `Backend`. 4. In the panel `Graphics backend` there is option tab labelled `Backend`.
5. By default this is set to `inline`, use the option arrors to change this to `Automatic`. 5. By default this is set to `inline`, use the option arrors to change this to `Automatic`.
6. Click `OK` tab at the bottom of the `Preferences` panel. 6. Click `OK` tab at the bottom of the `Preferences` panel.
*You will need to **restart** `Spyder` for this change to take effect.* *You will need to **restart** `Spyder` for this change to take effect.*
Now when you display graphics they will appear in a separate pop-up window with control icons. Now when you display graphics they will appear in a separate pop-up window with control icons.
<div> <div>
<img src="spyder_graphics.png" width="500"/> <img src="spyder_graphics.png" width="500"/>
</div> </div>
**Note: you only have to do this ONCE unless you do a `Reset to defaults` in the `Preferences`** **Note: you only have to do this ONCE unless you do a `Reset to defaults` in the `Preferences`**
> #### Other Preferences > #### Other Preferences
There are many-many other `Preferences` in `Spyder`, but this is the only one you will want to change. Many make rather complex changes to be behaviour; play with these with care, and if it all goes wrong, use the `Reset to defaults`. There are many-many other `Preferences` in `Spyder`, but this is the only one you will want to change. Many make rather complex changes to be behaviour; play with these with care, and if it all goes wrong, use the `Reset to defaults`.
Remember that some `Preference` changes take place immediately, but some of the major configuration changes require you to restart `Spyder`. Remember that some `Preference` changes take place immediately, but some of the major configuration changes require you to restart `Spyder`.
### Other routes ### Other routes
When `Python` is run from a terminal window on CPLab, Command Window in `Windows` or `Terminal` on `MacOS`, the `Matplotlib` plot automatically appears in its own window with controls. When `Python` is run from a terminal window on CPLab, Command Window in `Windows` or `Terminal` on `MacOS`, the `Matplotlib` plot automatically appears in its own window with controls.
## Interactive Display ## Interactive Display
A typical `Matplotlib` plot is shown below: A typical `Matplotlib` plot is shown below:
<div> <div>
<img src="cos_plot.png" width="500"/> <img src="cos_plot.png" width="500"/>
</div> </div>
You can move and resize this window by dragging the boundary. There are a set of tabs below the plot that allow pan/zoom, select rectangular area, change plot area and save as `png` file which you can then import into other systems, in particular $\LaTeX$ (which you will use for reports in later years). You can move and resize this window by dragging the boundary. There are a set of tabs below the plot that allow pan/zoom, select rectangular area, change plot area and save as `png` file which you can then import into other systems, in particular $\LaTeX$ (which you will use for reports in later years).
## Controlling the plot ## Controlling the plot
The default action is to plot the data with a red solid line, but this action can be changed by adding a third parameter to the call being a `str`, so, for example, it becomes. The default action is to plot the data with a red solid line, but this action can be changed by adding a third parameter to the call being a `str`, so, for example, it becomes.
```python ```python
plt.plot(xdata, ydata , "gx") plt.plot(xdata, ydata , "gx")
``` ```
The syntax of the control `str` is: The syntax of the control `str` is:
- First character is the colour, which can be `"r"`, (red), `"g"` (green), `"b"` (blue), `"k"` (black), etc, - First character is the colour, which can be `"r"`, (red), `"g"` (green), `"b"` (blue), `"k"` (black), etc,
- Second characters is the line or plot type, which can be `"-"` (solid line), (`"–"` (dashed line), `"x"` (cross marker), `"+"` (plus marker), etc. - Second characters is the line or plot type, which can be `"-"` (solid line), (`"–"` (dashed line), `"x"` (cross marker), `"+"` (plus marker), etc.
- The example above with `"gx"` plots the data with green cross-markers. - The example above with `"gx"` plots the data with green cross-markers.
There are many dozens of possibilities, which are listed at: `Matplotlib plot document page`. There are many dozens of possibilities, which are listed at: `Matplotlib plot document page`.
This also details the alternative route using keyword arguments, which allows even more options. This also details the alternative route using keyword arguments, which allows even more options.
You can also plot multiple set of data on one plot, so for example of you have two sets of y-data, called `firstydata` and `secondydata` then you can plot both sets of data on the one graph with You can also plot multiple set of data on one plot, so for example of you have two sets of y-data, called `firstydata` and `secondydata` then you can plot both sets of data on the one graph with
```python ```python
plt.plot(xdata, firstydata , "r" , xdata , secondydata, "g") plt.plot(xdata, firstydata , "r" , xdata , secondydata, "g")
``` ```
which will give a red line for `firstydata` and green line for `secondydata`. which will give a red line for `firstydata` and green line for `secondydata`.
> #### Code Examples > #### Code Examples
- Plot of $\cos(\theta)$ in the range 0→4π : [CosPlot](../CodeExamples/CosPlot.ipynb) >- Plot of $\cos(\theta)$ in the range 0→4π : [CosPlot](../CodeExamples/CosPlot.ipynb)
- Plot of flight of particle given inital velocity and acceleration : [FlightPlot](../CodeExamples/FlightPlot.ipynb) >- Plot of flight of particle given inital velocity and acceleration : [FlightPlot](../CodeExamples/FlightPlot.ipynb)
- Plot of a quadratic using a function: [QuadraticPlot](../CodeExamples/QuadraticPlot.ipynb) >- Plot of a quadratic using a function: [QuadraticPlot](../CodeExamples/QuadraticPlot.ipynb)
- More complex plot of a function using a function from the data `lists` >- More complex plot of a function using a function from the data `lists`
> Download and play with range, number of points and colours. > Have a look around and play with range, number of points and colours.
## Making Histograms ## Making Histograms
Another common plot you may want to produce is a histogram of the data held in a list of `float`s. If our lists of `float`s is called `numbers` and we wish to produce a histogram with 20 bins and evenly spaced between −3→3 then the code is: Another common plot you may want to produce is a histogram of the data held in a list of `float`s. If our lists of `float`s is called `numbers` and we wish to produce a histogram with 20 bins and evenly spaced between −3→3 then the code is:
```python ```python
plt.hist(numbers , bins = 20, range = [-3.0,3.0]) plt.hist(numbers , bins = 20, range = [-3.0,3.0])
plt.show() plt.show()
``` ```
This introduces the a new type of argument, called `kargs` or *keyword arguments*, in this case there are two: This introduces the a new type of argument, called `kargs` or *keyword arguments*, in this case there are two:
- `bins = 20` sets the number of bins, - `bins = 20` sets the number of bins,
- `range = [-3.0 , 3.0]` sets the argument `range` to a list that contains two floats, being the minumum and maximum value of the range of the *bins*. - `range = [-3.0 , 3.0]` sets the argument `range` to a list that contains two floats, being the minumum and maximum value of the range of the *bins*.
You will find this keyword argument syntax is often used in complex library functions where a function may take many dozens of different arguments and this methods simplifes the call. Note also the `kargs` can occur is any order, but must be after the normal arguments. You will find this keyword argument syntax is often used in complex library functions where a function may take many dozens of different arguments and this methods simplifes the call. Note also the `kargs` can occur is any order, but must be after the normal arguments.
> #### Code Examples > #### Code Examples
- Histogram plot of Gaussian random noise : >- [Histogram plot of Gaussian random noise](../CodeExamples/GaussianNoisePlot.ipynb)
> This uses the `random.gauss()` function that we introduced in `Adding Randoms`. > This uses the `random.gauss()` function that we introduced in `Adding Randoms`.
> Download and play with range, number of points and number of histogram bins. > Have a look around and play with range, number of points and number of histogram bins.
## Titles, Labels and Scale ## Titles, Labels and Scale
You can control and annotate your graph. You can add a *title* and *labels* to the x/y-axis with: You can control and annotate your graph. You can add a *title* and *labels* to the x/y-axis with:
```python ```python
plt.plot(<arguments to plot>) plt.plot(<arguments to plot>)
plt.title("Title of graph") plt.title("Title of graph")
plt.xlabel("Label for x axis") plt.xlabel("Label for x axis")
plt.ylabel("Label for y axis") plt.ylabel("Label for y axis")
plt.show() plt.show()
``` ```
you can also control the *limits* of the x/y-axis with you can also control the *limits* of the x/y-axis with
```python ```python
plt.xlim(-3.0,5.0) # set limit of xaxis to -3.0 -> 5.0 plt.xlim(-3.0,5.0) # set limit of xaxis to -3.0 -> 5.0
plt.ylim(0.0,100.0) # set limit of yaxis to 0.0 -> 100.0 plt.ylim(0.0,100.0) # set limit of yaxis to 0.0 -> 100.0
``` ```
There are many dozens of other commands, for example to change from linear to log scaling, add legends, vary axis ticks, add grids etc, all of which are documented in `Matplotlib pyplot summary`. There are many dozens of other commands, for example to change from linear to log scaling, add legends, vary axis ticks, add grids etc, all of which are documented in `Matplotlib pyplot summary`.
All these function calls must occur before the final `plt.show()`, which actually displays the graph. All these function calls must occur before the final `plt.show()`, which actually displays the graph.
This is all you need for making basic plots; Matplotlib is a very powerful and flexible package that will plot just about any type of graph / plot you can imagine. Look up the on-line examples in the Matpoltlib documentation and “play”. This is all you need for making basic plots; Matplotlib is a very powerful and flexible package that will plot just about any type of graph / plot you can imagine. Look up the on-line examples in the Matpoltlib documentation and “play”.
> You have now completed sufficient programming to attempt [Checkpoint 3](../Checkpoints/Checkpoint3.ipynb). > You have now completed sufficient programming to attempt [Checkpoint 3](../Checkpoints/Checkpoint3.ipynb).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id:776882d3 tags: %% Cell type:markdown id:776882d3 tags:
# What is a Computer Program # What is a Computer Program
## What is a Computer ? ## What is a Computer ?
Before we start teaching *computer programming* we need to first ask Before we start teaching *computer programming* we need to first ask
*what is a computer*. A simplfied structure of a computer is shown *what is a computer*. A simplfied structure of a computer is shown
below. below.
<div> <div>
<img src="png.png" width="500"/> <img src="png.png" width="500"/>
</div> </div>
The *Central Processing Unit* (CPU) operates on a series of instructions The *Central Processing Unit* (CPU) operates on a series of instructions
called a *program* which is stored in *memory*. The CPU consists of an called a *program* which is stored in *memory*. The CPU consists of an
*Arithmetic Logic Unit* (ALU) which performs such functions as addition, *Arithmetic Logic Unit* (ALU) which performs such functions as addition,
subtraction, comparison etc. and a *Control Unit* which directs and subtraction, comparison etc. and a *Control Unit* which directs and
monitors the operation of the computer. The *input* and *output* provide monitors the operation of the computer. The *input* and *output* provide
an interface to the outside world, for example the *input* may be the an interface to the outside world, for example the *input* may be the
keyboard and *output* the display screen. The *input* and *output* units keyboard and *output* the display screen. The *input* and *output* units
also provide access to data storage devices such as hard discs, DVDs, also provide access to data storage devices such as hard discs, DVDs,
USB devices etc. All these may be either connected directly to the USB devices etc. All these may be either connected directly to the
computer or over the *network*. computer or over the *network*.
The computer holds all information (numbers, letters, instructions) in The computer holds all information (numbers, letters, instructions) in
memory as patterns of binary bits, (ones and zeros). The instructions memory as patterns of binary bits, (ones and zeros). The instructions
are decoded by the *Control Unit* and determine what operations the ALU are decoded by the *Control Unit* and determine what operations the ALU
performs on the data. The desired sequence of instructions (the performs on the data. The desired sequence of instructions (the
*Program*) have to be placed in memory by the “programmer”, which is *Program*) have to be placed in memory by the “programmer”, which is
what we will be doing during this course. Remember that the computer is what we will be doing during this course. Remember that the computer is
a machine that exactly follows instructions and it is the sole a machine that exactly follows instructions and it is the sole
responsibility of the programmer to get these instructions right! responsibility of the programmer to get these instructions right!
The binary instructions used by the computer are not convenient for The binary instructions used by the computer are not convenient for
humans to use. This is further complicated by the fact that different humans to use. This is further complicated by the fact that different
computers use different sets of instructions. It is therefore much more computers use different sets of instructions. It is therefore much more
convenient to program in a *High Level Language* which is (more) humanly convenient to program in a *High Level Language* which is (more) humanly
readable and is independent of the details of the computer being used. readable and is independent of the details of the computer being used.
The high level language chosen for this course is . The high level language chosen for this course is .
From the model above the *program* is a set of instuctions that the From the model above the *program* is a set of instuctions that the
computer hardware implements in strict sequential order. computer hardware implements in strict sequential order.
## What is a program? ## What is a program?
### Key Point ### Key Point
The actual program is: The actual program is:
1. written in a *high level language* by the “programmer”, typically as 1. written in a *high level language* by the “programmer”, typically as
a text file, a text file,
2. converted into low level *machine instuctions*, 2. converted into low level *machine instuctions*,
3. loaded into memory, 3. loaded into memory,
4. executed by the hardware. 4. executed by the hardware.
so as a *programmer* you see only the *high level language*; all the so as a *programmer* you see only the *high level language*; all the
rest is handled for you by the *operating system*. rest is handled for you by the *operating system*.
> #### More details > #### More details
`Python` is an *interpreted language* which means that the >`Python` is an *interpreted language* which means that the
*conversion to low level machine instuctions*, *load into memory* all *conversion to low level machine instuctions*, *load into memory* all
occurs automatically *on the fly* as you execute the program, for occurs automatically *on the fly* as you execute the program, for
example with the command example with the command
```python >```python
python3 MyProgram.py python3 MyProgram.py
``` >```
from a Terminal Window. You do not have to worry about the underlying >from a Terminal Window. You do not have to worry about the underlying
details, particularly since we are running from Jupyter Notebooks in this course, but an understanding of what is “happening” is useful >details, particularly since we are running from Jupyter Notebooks in this course, but an understanding of what is “happening” is useful
when you are trying to work out why your program is not working…. >when you are trying to work out why your program is not working….
>In particular when things go wrong, has it failed during >In particular when things go wrong, has it failed during
1. conversion to low level instructions (syntax error), >1. conversion to low level instructions (syntax error),
2. during load (not able to find libraries or modules), >2. during load (not able to find libraries or modules),
3. or execution (did something numerically wrong). >3. or execution (did something numerically wrong).
There are more details on this in [Finding and fixing bugs](bugs.ipynb). >There are more details on this in [Finding and fixing bugs](bugs.ipynb).
### Key Point ### Key Point
So a *computer program* actually is So a *computer program* actually is
1. a set of instructions written in a precisely defined *language* with 1. a set of instructions written in a precisely defined *language* with
a very strict *syntax*, a very strict *syntax*,
2. implemented by *hardware* in a strict and precisely defined 2. implemented by *hardware* in a strict and precisely defined
sequential order. sequential order.
and it is the sole responsibility of the *programmer* to get this right. and it is the sole responsibility of the *programmer* to get this right.
This is why computer programing is *not easy*. This is why computer programing is *not easy*.
In this course you have to learn two things at the same time, these In this course you have to learn two things at the same time, these
being being
1. the syntax of the *language*; *this is mainly covered in the on-line 1. the syntax of the *language*; *this is mainly covered in the on-line
notes and examples* notes and examples*
2. how to formulate a problem in the required sequential order (program 2. how to formulate a problem in the required sequential order (program
design); *this is mainly covered in the mini-lectures*. This is design); *this is mainly covered in the mini-lectures*. This is
challenging part and a skill you will develop as progress through challenging part and a skill you will develop as progress through
this and subsequent courses. this and subsequent courses.
All of this will only start to come together as *you* work through this All of this will only start to come together as *you* work through this
course. course.
> #### (Apparent) similarity with mathematics > #### (Apparent) similarity with mathematics
When you look at the source for any *computer program* there is an *apparent* similarity with When you look at the source for any *computer program* there is an *apparent* similarity with
mathematics. There are *variables*, *functions* and signs; this can lead mathematics. There are *variables*, *functions* and signs; this can lead
novice programmers into a false sense of security…you are NOT *doing novice programmers into a false sense of security…you are NOT *doing
mathematics*, you *are* learning a new language that happens to use the mathematics*, you *are* learning a new language that happens to use the
same symbols! same symbols!
For example, the usage of ``=`` for assignment (see later) is very different from *equals* and can lead to quite hard to spot bugs.| For example, the usage of ``=`` for assignment (see later) is very different from *equals* and can lead to quite hard to spot bugs.|
......
%% Cell type:markdown id:7f60042b tags: %% Cell type:markdown id:7f60042b tags:
# Simple Lists # Simple Lists
In most programs you will want to manipulate more than one variable at a In most programs you will want to manipulate more than one variable at a
time, for example a set of x/y values that you want to plot or write to time, for example a set of x/y values that you want to plot or write to
a file. In this is handled by the which is a powerful and flexible a file. In this is handled by the which is a powerful and flexible
construct. In fact much of programming is the manipulation of . construct. In fact much of programming is the manipulation of .
We will start with a simple example; writing We will start with a simple example; writing
```python ```python
vals = [1.0, 2.0, 3.0, 5.0, 9.0, 4.0] vals = [1.0, 2.0, 3.0, 5.0, 9.0, 4.0]
print("Value of the 4th element is " + str(vals[3])) print("Value of the 4th element is " + str(vals[3]))
``` ```
will give `The value of the 4th element is 5.`. Looking at the syntax will give `The value of the 4th element is 5.`. Looking at the syntax
1. Creates a `list` called `vals` that has 6 items, all being `float`, that are denoted by `vals[0]` to `vals[5]`. Note the numbering starts at `0`! 1. Creates a `list` called `vals` that has 6 items, all being `float`, that are denoted by `vals[0]` to `vals[5]`. Note the numbering starts at `0`!
2. Prints the value of the 4th element, which is simply a `float` 2. Prints the value of the 4th element, which is simply a `float`
> The fact that lists number from “0” and the last element of a list of > The fact that lists number from “0” and the last element of a list of
length $L$ is at $L-1$ is just a “syntactic fact of life” and is common to all length $L$ is at $L-1$ is just a “syntactic fact of life” and is common to all
“C”-style languages. “C”-style languages.
This is one of the most common stumbling points for novice programmers; This is one of the most common stumbling points for novice programmers;
you just have to learn this and work with it! you just have to learn this and work with it!
A *list* superficially looks like a *vector*, but the index of the A *list* superficially looks like a *vector*, but the index of the
elements is different. elements is different.
> #### Starting from the end > #### Starting from the end
You can also access the elements of the `list` from *the You can also access the elements of the `list` from *the
end* using a $-$index, with `vals[-1]` being the *last* element, `vals[-2]` the *second last* end* using a $-$index, with `vals[-1]` being the *last* element, `vals[-2]` the *second last*
and so on. and so on.
It is not often you want to access a list this way, but `vals[-1]` is a very common It is not often you want to access a list this way, but `vals[-1]` is a very common
*short cut* syntax for the *last element*. *short cut* syntax for the *last element*.
We will see in the next section how to access lists in a loop, but first We will see in the next section how to access lists in a loop, but first
let’s consider some useful operations on the list from above: let’s consider some useful operations on the list from above:
```python ```python
vals.append(6.0) vals.append(6.0)
u = [12.0, 13.0, 14.0] u = [12.0, 13.0, 14.0]
vals.extend(u) vals.extend(u)
print("Length of vals is now " + str(len(vals))) print("Length of vals is now " + str(len(vals)))
w = vals[3:7] w = vals[3:7]
``` ```
where these statements will where these statements will
1. Append an element to the end of list `vals`, which will now have 7 1. Append an element to the end of list `vals`, which will now have 7
elements. elements.
2. Create a new list `u` with 3 elements. 2. Create a new list `u` with 3 elements.
3. Extend the list `vals` appending the contents of list `u` to the end of `vals`. 3. Extend the list `vals` appending the contents of list `u` to the end of `vals`.
4. Print the `len(vals)`, which gives the number of elements in `vals`. This will now be 10. 4. Print the `len(vals)`, which gives the number of elements in `vals`. This will now be 10.
5. Extract the elements of `vals` *starting* with `vals[3]` and *ending* at `vals[6]` and copy them to a new list `w`. Note that `w` will have 4 elements, watch the numbering! 5. Extract the elements of `vals` *starting* with `vals[3]` and *ending* at `vals[6]` and copy them to a new list `w`. Note that `w` will have 4 elements, watch the numbering!
## How to create a `list` ## How to create a `list`
There are many ways to create a list, but in simple programs there are There are many ways to create a list, but in simple programs there are
three typical routes: three typical routes:
1. Create a list of values or variables as above, for example 1. Create a list of values or variables as above, for example
```python ```python
x = 10.0 x = 10.0
y = 13.0 y = 13.0
z = 16.0 z = 16.0
v = [ x, y, z, 1.35] v = [ x, y, z, 1.35]
``` ```
will create a list of 4 `floats`. This is useful for short lists where you know what the elements will be. will create a list of 4 `floats`. This is useful for short lists where you know what the elements will be.
2. Create a list of *zero* length and then append what you want, so for 2. Create a list of *zero* length and then append what you want, so for
example with the same `x, y, z` you could write example with the same `x, y, z` you could write
```python ```python
v = [] v = []
v.append(x) v.append(x)
v.append(y) v.append(y)
v.append(z) v.append(z)
v.append(1.35) v.append(1.35)
``` ```
would give you the same list of 4 `floats`. This is not really useful in this example, but we will see this construct again when we start reading in data from a file where we don’t know how many elements we are going to read. would give you the same list of 4 `floats`. This is not really useful in this example, but we will see this construct again when we start reading in data from a file where we don’t know how many elements we are going to read.
3. Create a list of known length with all the elements being set the 3. Create a list of known length with all the elements being set the
the same value, this is done with the same value, this is done with
```python ```python
v = [0.0]*25 v = [0.0]*25
``` ```
which will create a list of 25 `floats` and set them all to $0.0$. Here they will be numbered $0\rightarrow24$. which will create a list of 25 `floats` and set them all to $0.0$. Here they will be numbered $0\rightarrow24$.
## Adding lists ## Adding lists
`lists` implements the `+` and `-` operators. This allows you to *add* lists together in a very obvious way, so you can write: `lists` implements the `+` and `-` operators. This allows you to *add* lists together in a very obvious way, so you can write:
```python ```python
a = [1,2,3,4,5] a = [1,2,3,4,5]
b = [7,8,9,10] b = [7,8,9,10]
c = a + b[1:3] c = a + b[1:3]
``` ```
gives `c` being a list containing the 5 elements of list `a` plus elements `[1], [2]` of list `b` so would be 7 elements long. gives `c` being a list containing the 5 elements of list `a` plus elements `[1], [2]` of list `b` so would be 7 elements long.
Similarly we can write Similarly we can write
```python ```python
a = [1,2,3,4,5] a = [1,2,3,4,5]
b = [7,8,9,10] b = [7,8,9,10]
a += b[0:2] a += b[0:2]
``` ```
where the operator `+=` in this case will extend list `a` with the first **two** elements of list `b`; so that where the operator `+=` in this case will extend list `a` with the first **two** elements of list `b`; so that
```python ```python
a = [1,2,3,4,5,7,8] a = [1,2,3,4,5,7,8]
``` ```
## Printing Lists ## Printing Lists
To print, you again do what you would expect; you can use the `str()` function to format the list as a `str` which you can print. So for example: To print, you again do what you would expect; you can use the `str()` function to format the list as a `str` which you can print. So for example:
```python ```python
a = [1,2,3,4,5,6] a = [1,2,3,4,5,6]
print("List a is : " + str(a)) print("List a is : " + str(a))
print("Elements 2 to 4 are : " + str(a[2:5])) print("Elements 2 to 4 are : " + str(a[2:5]))
``` ```
where the first `print` will format the all the elements of `a` surrounded by `[]` and the second `print` will format a three element sub-list of `a`. where the first `print` will format the all the elements of `a` surrounded by `[]` and the second `print` will format a three element sub-list of `a`.
There are many fancier ways to format the output of lists but this There are many fancier ways to format the output of lists but this
recipe will get you started and is a quick and effective way, especialy recipe will get you started and is a quick and effective way, especialy
if you want to print the contents of a list to monitor your program or if you want to print the contents of a list to monitor your program or
during debugging (which is often the case!). during debugging (which is often the case!).
> #### Other Types of Lists > #### Other Types of Lists
In the above example we have *only* considered lists of a single data type, being here `int` or `float`. However lists are much more In the above example we have *only* considered lists of a single data type, being here `int` or `float`. However lists are much more
flexible that this and you can create a list of *anything*, including flexible that this and you can create a list of *anything*, including
*lists-of-lists*, *lists-of-objects*, *list-of-functions* etc. *lists-of-lists*, *lists-of-objects*, *list-of-functions* etc.
>`Python` is also unique (?) in allowing lists of *mixed type*, so you can have mixture of any type of data in a single list, so `int`,`complex` `str`, and even other lists. It is, however, the sole responsibility of the programmer to *get >`Python` is also unique (?) in allowing lists of *mixed type*, so you can have mixture of any type of data in a single list, so `int`,`complex` `str`, and even other lists. It is, however, the sole responsibility of the programmer to *get
this right* and keep track of what each element actually is. This is a this right* and keep track of what each element actually is. This is a
very powerful and dangerous “feature” that sould be used with great very powerful and dangerous “feature” that sould be used with great
care, here there is almost unlimited scope for bugs which are obscure care, here there is almost unlimited scope for bugs which are obscure
and impossible to find!! and impossible to find!!
> Computationally intensive scientific programs typically use the `numpy` and `scipy` modules which use to hold numerical data; these are similar in but limited to fixed numerical types of a fixed length; you will learn about these in next year’s *Computer Modelling* course. > Computationally intensive scientific programs typically use the `numpy` and `scipy` modules which use to hold numerical data; these are similar in but limited to fixed numerical types of a fixed length; you will learn about these in next year’s *Computer Modelling* course.
>> **Code Examples:** >> **Code Examples:**
- Make and append to a list : [MakeandAppendList](../CodeExamples/MakeandAppendList.ipynb) >>- Make and append to a list : [MakeandAppendList](../CodeExamples/MakeandAppendList.ipynb)
- Extract sub lists and add lists together : [ExtractSublist](../CodeExamples/ExtractSublist.ipynb) >>- Extract sub lists and add lists together : [ExtractSublist](../CodeExamples/ExtractSublist.ipynb)
- Print a list : [PrintList](../CodeExamples/PrintList.ipynb) >>- Print a list : [PrintList](../CodeExamples/PrintList.ipynb)
This is just the start of lists and you will learn much more as you use This is just the start of lists and you will learn much more as you use
them. There are on-line examples: them. There are on-line examples:
1. `Python Informal Introduction` which contains a gentle explanation. 1. `Python Informal Introduction` which contains a gentle explanation.
2. `Python Data Structures` which contains more detail including some useful methods for example `.sort()` and `.reverse()` that act on the whole list. 2. `Python Data Structures` which contains more detail including some useful methods for example `.sort()` and `.reverse()` that act on the whole list.
## Lists and Functions ## Lists and Functions
You can use `lists` with `function`s, but you have to be slightly careful. Consider the code below to append two `lists`. You can use `lists` with `function`s, but you have to be slightly careful. Consider the code below to append two `lists`.
```python ```python
def append(first , second): def append(first , second):
l = first + second l = first + second
return l return l
def main(): def main():
first = [1,2,3,4,5] first = [1,2,3,4,5]
second = [6,7,8,9,10] second = [6,7,8,9,10]
nl = append(first,second) nl = append(first,second)
print(str(nl)) print(str(nl))
main() main()
``` ```
- Lines 1-3 define a `function` that takes two variables, adds them together and `returns` the result. - Lines 1-3 define a `function` that takes two variables, adds them together and `returns` the result.
- Lines 5-9 define two `list`s, pass them to the function which forms a new `list` called `l`, being the addition of the `lists`, which it `returns`. - Lines 5-9 define two `list`s, pass them to the function which forms a new `list` called `l`, being the addition of the `lists`, which it `returns`.
- Line 11 then runs the `main` program. - Line 11 then runs the `main` program.
This works exactly as expected and the returned `list` called `nl` on line 8 is the copy of list `first` and `second` added together, so is a `list` of 10 elements holding the numbers $1\rightarrow9$. This works exactly as expected and the returned `list` called `nl` on line 8 is the copy of list `first` and `second` added together, so is a `list` of 10 elements holding the numbers $1\rightarrow9$.
> Experiment with the following `append` fuction, and see that it also works for other variable types. > Experiment with the following `append` fuction, and see that it also works for other variable types.
- Code of [AppendFunction](../CodeExamples/AppendFunction.ipynb). >- Code of [AppendFunction](../CodeExamples/AppendFunction.ipynb).
However things get a little more complicated if you pass a `list` into a `function`, and then change values in the `list`, so for example consider the following piece of code that sorts the contents of a `list`: However things get a little more complicated if you pass a `list` into a `function`, and then change values in the `list`, so for example consider the following piece of code that sorts the contents of a `list`:
```python ```python
def sortit(ls): def sortit(ls):
ls.sort() ls.sort()
def main(): def main():
vals = [2,7,6,9,1] vals = [2,7,6,9,1]
sortit(vals) sortit(vals)
print(str(vals)) print(str(vals))
main() main()
``` ```
- Lines 1-2 define a `function` that will sort a `list` into ascending order using the `.sort()` method. - Lines 1-2 define a `function` that will sort a `list` into ascending order using the `.sort()` method.
- Lines 4-7 show the use of this `function` to sort a `list` of integers. - Lines 4-7 show the use of this `function` to sort a `list` of integers.
So in this case changes made to contents of the `list` inside the `function`, change the contents of the `list` in the `main()` program. So in this case changes made to contents of the `list` inside the `function`, change the contents of the `list` in the `main()` program.
> #### What is really happening > #### What is really happening
This initially looks inconsistent as it looks like `lists` behave differently from variables like `float` or `int`. The answer to this is This initially looks inconsistent as it looks like `lists` behave differently from variables like `float` or `int`. The answer to this is
“What is being passed to the function”. “What is being passed to the function”.
- For the basic built-in variables, a copy of the value is passed to - For the basic built-in variables, a copy of the value is passed to
the `function`. This means that any changes to the variable value inside the `function` do not change the value in the calling program. the `function`. This means that any changes to the variable value inside the `function` do not change the value in the calling program.
- For compound variable types, for example `lists`, a copy of the location is passed, so that the elements of the `list` are visible, and can be changed inside the `function`. - For compound variable types, for example `lists`, a copy of the location is passed, so that the elements of the `list` are visible, and can be changed inside the `function`.
> This sounds a lot more complex that it is, and it normally does what you expect, but confusing this aspect of the language can result in complex and hard to find bugs. > This sounds a lot more complex that it is, and it normally does what you expect, but confusing this aspect of the language can result in complex and hard to find bugs.
>> Download these two example and convince yourself you understand what is happening >> Play with these two examples and convince yourself you understand what is happening
- Use of an `append` function for `list` and `float` >>- Use of an `append` function for `list` and `float`
- Use of a `sort` function for `list` >>- Use of a `sort` function for `list`
The second of these is rather tricky, try and work out what is >>The second of these is rather tricky, try and work out what is happening!
happening!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id:033593dd tags: %% Cell type:markdown id:033593dd tags:
# Printing and Reading to/from the Terminal # Printing and Reading to/from the Terminal
## Print to the terminal ## Print to the terminal
Let’s look at how to print to the terminal using the `print()` function. This Let’s look at how to print to the terminal using the `print()` function. This
prints a `str`, so for example: prints a `str`, so for example:
```python ```python
print("Hello world") print("Hello world")
f = "Fred" f = "Fred"
g = "Ginger" g = "Ginger"
print("The dancers were " + f + " and " + g) print("The dancers were " + f + " and " + g)
``` ```
The first line will print `Hello world` and the fourth will form a string containing `The dancers were Fred and Ginger` and then print it to the terminal, in both cases followed by a newline. The first line will print `Hello world` and the fourth will form a string containing `The dancers were Fred and Ginger` and then print it to the terminal, in both cases followed by a newline.
The `print()` function is most useful is when it is combined with the `str()` function, which converts other data types into `str` so allowing them to be easily printed, for example: The `print()` function is most useful is when it is combined with the `str()` function, which converts other data types into `str` so allowing them to be easily printed, for example:
```python ```python
radius = 63.256 radius = 63.256
print("The radius is : " + str(radius)) print("The radius is : " + str(radius))
z = 16.56 + 74.4j z = 16.56 + 74.4j
print("Complex value is : " + str(z)) print("Complex value is : " + str(z))
``` ```
In both lines two and four the `str()` function forms a string from the In both lines two and four the `str()` function forms a string from the
numerical variable which is appended to the `str` in quotes and printed in a numerical variable which is appended to the `str` in quotes and printed in a
reasonable format. reasonable format.
### Key Point ### Key Point
The simplest route to print the value of any variable is to: The simplest route to print the value of any variable is to:
- convert it to a str using the `str()` function, - convert it to a str using the `str()` function,
- then use the `print()` function to print the `str`. - then use the `print()` function to print the `str`.
A fancier route is the `str.format(`) function, which is covered in `Formatting` section with many options to format your `str`, but this is not needed for this course. A fancier route is the `str.format(`) function, which is covered in `Formatting` section with many options to format your `str`, but this is not needed for this course.
> Write yourself a test program to output your name and address to the terminal. > Write yourself a test program to output your name and address to the terminal.
> **The `print` without the brackets you will find in many on-line examples is the > **The `print` without the brackets you will find in many on-line examples is the
old syntax; do not use it, or your code will NOT work!!! old syntax; do not use it, or your code will NOT work!!!
## Reading input from the terminal ## Reading input from the terminal
To get input from the terminal we use the `input()` function. This reads a `str` from the terminal, so for example: To get input from the terminal we use the `input()` function. This reads a `str` from the terminal, so for example:
```python ```python
name = input("Type your name : ") name = input("Type your name : ")
print(name) print(name)
``` ```
This will prompt you at the terminal with `"Type your name : "`. It will read this into to `str` variable `name` and then print it back. This will prompt you at the terminal with `"Type your name : "`. It will read this into to `str` variable `name` and then print it back.
> **Example Code:** Reading and printing out a string: [ReadingandPrintingStrings](../CodeExamples/ReadingandPrintingStrings.ipynb) > **Example Code:** Reading and printing out a string: [ReadingandPrintingStrings](../CodeExamples/ReadingandPrintingStrings.ipynb)
Note: the lines that start with `#` are *comments* and do not form part of Note: the lines that start with `#` are *comments* and do not form part of
the code. Try running the code example to see what it does. the code. Try running the code example to see what it does.
The `input()` function really becomes useful when you combine it with the `float()`, `int()` or `complex()` functions to read numerical values from the terminal, so for example The `input()` function really becomes useful when you combine it with the `float()`, `int()` or `complex()` functions to read numerical values from the terminal, so for example
```python ```python
n = int(input("Number of circles : ")) n = int(input("Number of circles : "))
radius = float(input("Give the radius : ")) radius = float(input("Give the radius : "))
``` ```
- **Line one** will prompt for the `Number of circles : ` and read the typed value into variable `n` which will be an `int`. - **Line one** will prompt for the `Number of circles : ` and read the typed value into variable `n` which will be an `int`.
- **Line two** will prompt for `Give the radius : ` and read the typed value into the variable `radius` which will be a `float`. - **Line two** will prompt for `Give the radius : ` and read the typed value into the variable `radius` which will be a `float`.
> When reading `int` or `float` the use of `int(input(…))` or `float(input(…))` is required to ensure you get the correct variable type. > When reading `int` or `float` the use of `int(input(…))` or `float(input(…))` is required to ensure you get the correct variable type.
This is **NEW** in `Python-3`, you will find old `Python-2` code online that just used `input(…)` to read `int` and `float`s, but this will not work in Python-3. This is **NEW** in `Python-3`, you will find old `Python-2` code online that just used `input(…)` to read `int` and `float`s, but this will not work in Python-3.
This is your first taste of interactive programming. This is your first taste of interactive programming.
> **Old- issue**: There is a subtle `Python-2` to `Python-3` issue here. In `Python-2` the string returned by `input()` is automatically evaluated by the `eval()` function before being returned where in `Python-3` it is returned as typed. > **Old- issue**: There is a subtle `Python-2` to `Python-3` issue here. In `Python-2` the string returned by `input()` is automatically evaluated by the `eval()` function before being returned where in `Python-3` it is returned as typed.
Basic programmers will *not* notice the difference and the implications Basic programmers will *not* notice the difference and the implications
of this are beyond the scope of this course. of this are beyond the scope of this course.
>> **Example Code :** >> **Example Code :**
- Reading and printing floats: [ReadingandPrintingFloats](../CodeExamples/ReadingandPrintingFloats.ipynb) >>- Reading and printing floats: [ReadingandPrintingFloats](../CodeExamples/ReadingandPrintingFloats.ipynb)
- Reading and formatting floats: [ReadingandFormatFloats](../CodeExamples/ReadingandFormatFloats.ipynb) >>- Reading and formatting floats: [ReadingandFormatFloats](../CodeExamples/ReadingandFormatFloats.ipynb)
- Reading int and float : (more complicated example) [ReadingIntandFloat](../CodeExamples/ReadingIntandFloat.ipynb) >>- Reading int and float : (more complicated example) [ReadingIntandFloat](../CodeExamples/ReadingIntandFloat.ipynb)
Download and run these programs; also try giving the wrong input types >>Download and run these programs; also try giving the wrong input types
and see what happens. It will *crash* with a *Traceback* which is >>and see what happens. It will *crash* with a *Traceback* which is
**not** friendly; try this out and learn to make sense of this, you will >>**not** friendly; try this out and learn to make sense of this, you will
see this a lot in your programming career, so it helps to make sense now of some of the messages you will see. >>see this a lot in your programming career, so it helps to make sense now of some of the messages you will see.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Week Five # Week Five
## Online mini-lecture ## Online mini-lecture
Please watch the following online mini-lecture: Please watch the following online mini-lecture:
- [SciProg - L05 - Functions and Lists (video)](https://ed-ac-uk.zoom.us/rec/share/ckl9Gj8YuPVbaC2dXCjEJA9wVaARETkvP53NE1ivr_s_R2ZKntu-Rpb3bzWTgOkI.mSWzj2ScX9GJPZ99?startTime=1663597243000) - [SciProg - L05 - Functions and Lists (video)](https://ed-ac-uk.zoom.us/rec/share/ckl9Gj8YuPVbaC2dXCjEJA9wVaARETkvP53NE1ivr_s_R2ZKntu-Rpb3bzWTgOkI.mSWzj2ScX9GJPZ99?startTime=1663597243000)
- [SciProg - L05 - Functions and Lists (pdf)](../Slides/sciprog-L05-functions-lists.pdf) - [SciProg - L05 - Functions and Lists (pdf)](../Slides/sciprog-L05-functions-lists.pdf)
## Course notes ## Course notes
Study the following sections of the course notes before your workshop session: Study the following sections of the course notes before your workshop session:
- [More Functions](../CourseNotes/MoreFunctions.ipynb) - [More Functions](../CourseNotes/MoreFunctions.ipynb)
- [Functions and Lists](../CourseNotes/FunctionsAndLists.ipynb)
- Preread [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb) and in particular the suggested code structure in the Hint. - Preread [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb) and in particular the suggested code structure in the Hint.
## Multiple choice questions ## Multiple choice questions
Ensure you have completed the on-line quiz [MCQ Test 4](https://www.learn.ed.ac.uk/ultra/courses/_117833_1/outline/assessment/_10718529_1/overview?) Ensure you have completed the on-line quiz [MCQ Test 4](https://www.learn.ed.ac.uk/ultra/courses/_117833_1/outline/assessment/_10718529_1/overview?)
## Workshop ## Workshop
In the workshop you should: In the workshop you should:
1. Work through the example codes in Further Functions and make sure you understand them. If you have time look at those in More Complex. 1. Work through the example codes in Further Functions and make sure you understand them. If you have time look at those in More Complex.
2. Do [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb). Check carefully that you have the correct structure for checkpoint 5 in the Hint and also think carefully what you need to store in lists. 2. Do [Checkpoint 5](../Checkpoints/Checkpoint5.ipynb). Check carefully that you have the correct structure for checkpoint 5 in the Hint and also think carefully what you need to store in lists.
3. Have Checkpoint 5 assessed and checked off by a TA. 3. Have Checkpoint 5 assessed and checked off by a TA.
## Do before next week ## Do before next week
<!--- <!---
The tasks do to before the next session are: The tasks do to before the next session are:
1. Complete the on-line [MCQ Test 5](https://www.learn.ed.ac.uk/ultra/courses/_108405_1/outline/assessment/_9430171_1/overview?courseId=_108405_1) 1. Complete the on-line [MCQ Test 5](https://www.learn.ed.ac.uk/ultra/courses/_108405_1/outline/assessment/_9430171_1/overview?courseId=_108405_1)
2. Please watch the following online mini-lecture: 2. Please watch the following online mini-lecture:
- [SciProg - L06 - More advanced python (video)](https://ed-ac-uk.zoom.us/rec/share/vXCNX_qCmIMJgrBboGOGmyhNixP1CnPDzbf4KnltD9bt_n2GQWWJFQ2Q0qSKzexz.-CDImVCmIaYjwilk?startTime=1663597908000) - [SciProg - L06 - More advanced python (video)](https://ed-ac-uk.zoom.us/rec/share/vXCNX_qCmIMJgrBboGOGmyhNixP1CnPDzbf4KnltD9bt_n2GQWWJFQ2Q0qSKzexz.-CDImVCmIaYjwilk?startTime=1663597908000)
- [SciProg - L06 - More advanced python (pdf)](../Slides/sciprog-L06-more-python.pdf) - [SciProg - L06 - More advanced python (pdf)](../Slides/sciprog-L06-more-python.pdf)
3. Read the following sections of the notes: 3. Read the following sections of the notes:
>- [Scope of Variables](../CourseNotes/Scope.ipynb) >- [Scope of Variables](../CourseNotes/Scope.ipynb)
>- [Lambda Functions](../CourseNotes/lambda.ipynb) >- [Lambda Functions](../CourseNotes/lambda.ipynb)
>- [Map and Zip](../CourseNotes/AdvancedListProcessing.ipynb) >- [Map and Zip](../CourseNotes/AdvancedListProcessing.ipynb)
>- [Objects](../CourseNotes/ObjectsandOOP.ipynb) >- [Objects](../CourseNotes/ObjectsandOOP.ipynb)
4. Explore the code example themes ***More Complex***, ***Scope*** and ***Objects*** from [here](../CodeExamples/CodeExamples.ipynb). 4. Explore the code example themes ***More Complex***, ***Scope*** and ***Objects*** from [here](../CodeExamples/CodeExamples.ipynb).
5. 5.
--> -->
Continue your journey through this course by looking at [Week 6](Week6.ipynb). Continue your journey through this course by looking at [Week 6](Week6.ipynb).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......