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 October at 12:00PM
    • Due Wednesday 22nd October at 12:00PM
  • 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 Fetch and 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 x in
  • It doubles x and adds 1
  • Then prints the result

Functions

  • Suppose we now run this code after the function.
  • This will run the code inside the function, but with x replaced by k.
    • 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:
    • x is an input: A variable specified in the function definition
    • y is an output: A variable given back using the return statement
  • You can have multiple inputs and outputs (we’ll cover this in the practical)

Practical