Introduction to Coding and Data Analysis for Scientists
Week 4: Functions
Today’s Lecture
- Lecture 4: Functions
- Recap: For and While Loops
- Functions
- Inputs and Outputs
- Practical
Important: Assessed Coursework 1
- The first assignment has been released!
- Released
Wednesday 8th Octoberat12:00PM - Due
Wednesday 22nd Octoberat12:00PM
- Released
- This is assessed (
15%of your grade!) - Submission is via
Noteable - You can submit as many times as you like up until the submission date
Noteable Submission
- Download using the Assignments tab on
noteable - Press
Fetchand click on the assignment - Fill your answers in and
Validate - Once done, save your answers and
Submit - Feedback will be available when you see the
(view feedback)option
Recap: for and while loops
- Loops can be used to simplify repetitive computation
- Last week, we saw an example where we wanted to print the square of each item in this list
- We could write code like this…
Recap: for and while loops
- Loops let us do all this automatically!
Motivation
- Loops let you simplify code which repeats over and over again.
- However, sometimes you have code that repeats itself in a less straightforward manner…
- Do some computation
- Run some other code
- Do the same computation again
- In such cases, you might want to use a
function - You can think of a function as a block of pre-prepared code that you might want to run over and over again.
Functions
- Let’s look at an example.
You can think of this as a black box
- You put a variable
xin - It doubles
xand adds1 - Then prints the result
Functions
- Suppose we now run this code after the function.
- This will run the code inside the function, but with
xreplaced byk.- E.g. it will run:
y = k * 2 + 1
print(y)Functions
- We can use this function to simplify the code from earlier!
Motivation
- Functions are useful for a number of reasons
- Reduce repetitiveness in code
- Help organise code
- Easier to edit, maintain and debug
- Makes code easier to share
- Improve readability
Inputs and Outputs
- Instead of printing the result of our function, we can return it
- This means that the function will “spit out” the value of
y, and we can save it using the=operator
- For this example:
xis aninput: A variable specified in the function definitionyis anoutput: A variable given back using thereturnstatement
- You can have multiple inputs and outputs (we’ll cover this in the practical)
Practical
- We now move over to Python
- Please open week_04_home.ipynb
- For the rest of today, you must work through a Python notebook
- You have a choice of one of three options