"***Acknowledgements: Many thanks to Emily Santis Okell for providing very useful feedback.***\n",
"\n",
"*Target audience: people with no or little programming experience*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Where am I?\n",
"\n",
"You are looking at a jupyter notebook. This a convenient way of programming in the python language from within a web browser, mixed with with some text like this! You should have launched this page from a terminal using:\n",
"\n",
"`cd directory/containing/this/file/`\n",
"\n",
"`fslpython -m notebook`\n",
"\n",
"Then clicking on `intro_to_programming.ipynb`\n",
"\n",
"Note that you can run python in other ways too, but this is convenient for now!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What are we doing here?\n",
"\n",
"Below are some very simple examples of programming concepts. Here we are using the python programming language. Please don't worry if the exact way things are written is a little unclear: the following sessions will go into a lot more detail about exactly how you write code in python. For now, we are just focussing on the concepts!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variables\n",
"\n",
"A variable is a \"container\" for some information. We can assign a value to a variable using the equals \"=\" sign:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This is a block of python code that you can execute within this browser window\n",
"# by clicking on it and then hitting shift+enter. Anything after a hash (#) is a\n",
"# comment and is ignored when the code is run. You can modify any of the code\n",
"# below and re-run it with shift+enter to see what happens! Let's define a \n",
"# variable called \"a\" that we give the value 3:\n",
"a = 3\n",
"# We can change the value assigned to the variable \"a\" at any time:\n",
"a = 4\n",
"# We can define a variable to contain a character, like this:\n",
"a = 's'\n",
"# Or a set of characters, known as a string:\n",
"a = 'hello'\n",
"# We can define another variable, b, and give it the same value as a:\n",
"b = a\n",
"# If a is a number, we can do some simple maths:\n",
"# Here b is given a value one more than a, and c is given a value twice\n",
"# the size of a (note that * is used for \"multiply\" in python):\n",
"a = 3\n",
"b = a + 1\n",
"c = 2 * a\n",
"# If you want to show the value of a variable, you can do it like this:\n",
"print('a has the value',a)\n",
"print('b has the value',b)\n",
"print('c has the value',c)\n",
"# Note that 'print' here means 'print to the screen', not 'print to a printer'!\n",
"# The output should appear just below this block after you hit shift+enter:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Flow control: the \"if\" statement\n",
"\n",
"We can control the 'flow' (i.e. which bits of code get executed and which don't and the order in which they happen) of the program we write using a number of simple statements, like the \"if\" statement:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We can do something based on the value of a variable\n",
"# For example, if the variable a is a number larger than 10, \n",
"# then say \"big!\", otherwise say \"small\"\n",
"a = 11\n",
"if a > 10: \n",
" print('big!')\n",
"else: \n",
" print('small!')\n",
" \n",
"# You can try changing the value of a above the \"if\" statement to make sure this\n",
"# works as expected!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Flow control: a \"for\" loop\n",
"\n",
"For repetitive tasks, loops such as the \"for\" loop are extremely useful:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# In this case we want to repeat the statements below the \"for\" many times. Each\n",
"# time, the value stored in the variable \"a\" changes, starting from 1 and ending\n",
"# before 10 (so 9 is the last value of a in this case). Here we simply \"print\"\n",
"# the value of a to the screen each time we go around the loop.\n",
"for a in range(1,10):\n",
" print(a)\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Functions\n",
"\n",
"Writing lots of code as one huge file can get rather messy! You will often find that you want to perform some specific task multiple times within the same bit of code, so it can be very useful to define a \"function\", which takes some inputs, performs some operations and then returns some output. Here's a very simple example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Define a function that returns the number passed into it squared:\n",
"def square_my_number(a):\n",
" a_squared = a * a\n",
" return a_squared\n",
"# Note that in the above code the variable \"a\" is only used internally \n",
"# within the function and just represents whatever number has been passed\n",
"# into the function as its input. That number might be stored in another variable \n",
"# with a different name in the code that calls the function, as you will see below.\n",
"# In other words, you don't have to only use this function with a variable \n",
"# called \"a\"!\n",
"\n",
"# We can now use this function however many times we wish:\n",
"n = 3\n",
"# Here we \"call\" the \"square_my_number\" function, passing in the value of n as\n",
"# input. The function returns n squared and this value is stored in a new\n",
"# variable which we've called n_squared here:\n",
"n_squared = square_my_number(n)\n",
"print('n is',n,'and n_squared is',n_squared)\n",
"\n",
"# Do the same thing again for a different variable, m:\n",
"m = 4\n",
"m_squared = square_my_number(m)\n",
"print('m is',m,'and m_squared is',m_squared)\n",
"\n",
"# Although this is a very simple example, hopefully you can see that if\n",
"# square_my_number was a much more complicated procedure, it would be a lot\n",
"# easier and neater to define the function and then call it once using n and\n",
"# once using m, rather than copying all of the code applied to n and writing it\n",
"# again to apply to m."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using code from packages\n",
"\n",
"There are tonnes of extremely useful bits of code which have been conveniently packaged up for you! Don't worry about the details here, but as an example we \"import\" the predefined package called \"numpy\", which can do all sorts of clever bits of maths:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import the numpy package so we can use it in the code below:\n",
"import numpy as np\n",
"\n",
"# Define a variable called \"data\" which contains a set or \"array\" of numbers \n",
"# using numpy\n",
"data = np.array([10, 8, 12, 14, 7, 6, 11])\n",
"\n",
"# Numpy can do lots of cool things, including the one dimensional Fast Fourier\n",
"# Transform (FFT)! Here the Fourier transform of the numbers in the array \"data\"\n",
"# are calculated and then stored in a new variable called \"ftdata\":\n",
"ftdata = np.fft.fft(data)\n",
"\n",
"# Note that we could have defined our own function to perform the Fourier\n",
"# Transform if we wanted to, but it's very convenient that a lot of these\n",
"# complicated algorithms have already been implemented in a fast and efficient\n",
"# way."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## If you have time, let's use programming to perform a boring, repetitive task...\n",
"\n",
"Say we want to input ***1~100*** into a text (***.txt***) file, but we don't want repetitively press the keyboard hundreds of times (and probably make a mistake...), here's what we could do!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's start with a simple of example of writing a single number into a text file:\n",
"Here we want to have a text file called *'temp.txt'* in the current directory, and the content of the file is just single character *1*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Define the number to write and store in a variable, a\n",
"a = 1\n",
"# Open the file to allow us to write into it\n",
"f = open('temp.txt','w')\n",
"# Write the value in variable a to the file\n",
"# Don't worry about the exact form of the code below - you'll learn more about\n",
"# this later!\n",
"f.write(f'{a}' + '\\n')\n",
"# Close the file\n",
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Now let's use a for loop to write the numbers 1~100 into the file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Open the file\n",
"f = open('temp.txt','w')\n",
"\n",
"# Loop through the values we want using variable \"a\"\n",
"# Remember the way \"range\" works here is to go up to but\n",
"# not including the number you specify, so if we want to stop\n",
"# at 100, we use range(1,101)\n",
"for a in range(1,101):\n",
" # Write the value into the file\n",
" f.write(f'{a}' + '\\n')\n",
"\n",
"# Close the file\n",
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can check the contents of that file in your terminal by running:\n",
"\n",
"`cat temp.txt`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Now imagine we want to write ***1~100*** but exclude number 6\n",
"\n",
"We can achieve this fairly easily using a simple if statement:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Open file\n",
"f = open('temp.txt','w')\n",
"\n",
"# Loop through the values we want\n",
"for a in range(1,101):\n",
" \n",
" # Here we can use an \"if\" statement to only write the number into the \n",
" # file if it is not 6. Note that in python \"!=\" means \"not equal to\" \n",
" # so the code below only executes if a is not 6\n",
" if a != 6:\n",
" \n",
" # Write the value into the file\n",
" f.write(f'{a}' + '\\n')\n",
"\n",
"# Close the file\n",
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Again, you can check the contents of that file in your terminal by running:\n",
"\n",
"`cat temp.txt`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Done!\n",
"Well done on making it this far! As mentioned above, don't worry too much if the exact way the code is written wasn't totally clear. The following sessions will discuss in more detail exactly how to write code in python, but hopefully this has given you an idea of the kinds of basic structures used in programming that you will use in future sessions."
***Acknowledgements: Many thanks to Emily Santis Okell for providing very useful feedback.***
*Target audience: people with no or little programming experience*
%% Cell type:markdown id: tags:
## Where am I?
You are looking at a jupyter notebook. This a convenient way of programming in the python language from within a web browser, mixed with with some text like this! You should have launched this page from a terminal using:
`cd directory/containing/this/file/`
`fslpython -m notebook`
Then clicking on `intro_to_programming.ipynb`
Note that you can run python in other ways too, but this is convenient for now!
%% Cell type:markdown id: tags:
## What are we doing here?
Below are some very simple examples of programming concepts. Here we are using the python programming language. Please don't worry if the exact way things are written is a little unclear: the following sessions will go into a lot more detail about exactly how you write code in python. For now, we are just focussing on the concepts!
%% Cell type:markdown id: tags:
## Variables
A variable is a "container" for some information. We can assign a value to a variable using the equals "=" sign:
%% Cell type:code id: tags:
``` python
# This is a block of python code that you can execute within this browser window
# by clicking on it and then hitting shift+enter. Anything after a hash (#) is a
# comment and is ignored when the code is run. You can modify any of the code
# below and re-run it with shift+enter to see what happens! Let's define a
# variable called "a" that we give the value 3:
a=3
# We can change the value assigned to the variable "a" at any time:
a=4
# We can define a variable to contain a character, like this:
a='s'
# Or a set of characters, known as a string:
a='hello'
# We can define another variable, b, and give it the same value as a:
b=a
# If a is a number, we can do some simple maths:
# Here b is given a value one more than a, and c is given a value twice
# the size of a (note that * is used for "multiply" in python):
a=3
b=a+1
c=2*a
# If you want to show the value of a variable, you can do it like this:
print('a has the value',a)
print('b has the value',b)
print('c has the value',c)
# Note that 'print' here means 'print to the screen', not 'print to a printer'!
# The output should appear just below this block after you hit shift+enter:
```
%% Cell type:markdown id: tags:
## Flow control: the "if" statement
We can control the 'flow' (i.e. which bits of code get executed and which don't and the order in which they happen) of the program we write using a number of simple statements, like the "if" statement:
%% Cell type:code id: tags:
``` python
# We can do something based on the value of a variable
# For example, if the variable a is a number larger than 10,
# then say "big!", otherwise say "small"
a=11
ifa>10:
print('big!')
else:
print('small!')
# You can try changing the value of a above the "if" statement to make sure this
# works as expected!
```
%% Cell type:markdown id: tags:
## Flow control: a "for" loop
For repetitive tasks, loops such as the "for" loop are extremely useful:
%% Cell type:code id: tags:
``` python
# In this case we want to repeat the statements below the "for" many times. Each
# time, the value stored in the variable "a" changes, starting from 1 and ending
# before 10 (so 9 is the last value of a in this case). Here we simply "print"
# the value of a to the screen each time we go around the loop.
forainrange(1,10):
print(a)
```
%% Cell type:markdown id: tags:
## Functions
Writing lots of code as one huge file can get rather messy! You will often find that you want to perform some specific task multiple times within the same bit of code, so it can be very useful to define a "function", which takes some inputs, performs some operations and then returns some output. Here's a very simple example:
%% Cell type:code id: tags:
``` python
# Define a function that returns the number passed into it squared:
defsquare_my_number(a):
a_squared=a*a
returna_squared
# Note that in the above code the variable "a" is only used internally
# within the function and just represents whatever number has been passed
# into the function as its input. That number might be stored in another variable
# with a different name in the code that calls the function, as you will see below.
# In other words, you don't have to only use this function with a variable
# called "a"!
# We can now use this function however many times we wish:
n=3
# Here we "call" the "square_my_number" function, passing in the value of n as
# input. The function returns n squared and this value is stored in a new
# variable which we've called n_squared here:
n_squared=square_my_number(n)
print('n is',n,'and n_squared is',n_squared)
# Do the same thing again for a different variable, m:
m=4
m_squared=square_my_number(m)
print('m is',m,'and m_squared is',m_squared)
# Although this is a very simple example, hopefully you can see that if
# square_my_number was a much more complicated procedure, it would be a lot
# easier and neater to define the function and then call it once using n and
# once using m, rather than copying all of the code applied to n and writing it
# again to apply to m.
```
%% Cell type:markdown id: tags:
## Using code from packages
There are tonnes of extremely useful bits of code which have been conveniently packaged up for you! Don't worry about the details here, but as an example we "import" the predefined package called "numpy", which can do all sorts of clever bits of maths:
%% Cell type:code id: tags:
``` python
# Import the numpy package so we can use it in the code below:
importnumpyasnp
# Define a variable called "data" which contains a set or "array" of numbers
# using numpy
data=np.array([10,8,12,14,7,6,11])
# Numpy can do lots of cool things, including the one dimensional Fast Fourier
# Transform (FFT)! Here the Fourier transform of the numbers in the array "data"
# are calculated and then stored in a new variable called "ftdata":
ftdata=np.fft.fft(data)
# Note that we could have defined our own function to perform the Fourier
# Transform if we wanted to, but it's very convenient that a lot of these
# complicated algorithms have already been implemented in a fast and efficient
# way.
```
%% Cell type:markdown id: tags:
## If you have time, let's use programming to perform a boring, repetitive task...
Say we want to input ***1~100*** into a text (***.txt***) file, but we don't want repetitively press the keyboard hundreds of times (and probably make a mistake...), here's what we could do!
%% Cell type:markdown id: tags:
Let's start with a simple of example of writing a single number into a text file:
Here we want to have a text file called *'temp.txt'* in the current directory, and the content of the file is just single character *1*
%% Cell type:code id: tags:
``` python
# Define the number to write and store in a variable, a
a=1
# Open the file to allow us to write into it
f=open('temp.txt','w')
# Write the value in variable a to the file
# Don't worry about the exact form of the code below - you'll learn more about
# this later!
f.write(f'{a}'+'\n')
# Close the file
f.close()
```
%% Cell type:markdown id: tags:
## Now let's use a for loop to write the numbers 1~100 into the file
%% Cell type:code id: tags:
``` python
# Open the file
f=open('temp.txt','w')
# Loop through the values we want using variable "a"
# Remember the way "range" works here is to go up to but
# not including the number you specify, so if we want to stop
# at 100, we use range(1,101)
forainrange(1,101):
# Write the value into the file
f.write(f'{a}'+'\n')
# Close the file
f.close()
```
%% Cell type:markdown id: tags:
You can check the contents of that file in your terminal by running:
`cat temp.txt`
%% Cell type:markdown id: tags:
## Now imagine we want to write ***1~100*** but exclude number 6
We can achieve this fairly easily using a simple if statement:
%% Cell type:code id: tags:
``` python
# Open file
f=open('temp.txt','w')
# Loop through the values we want
forainrange(1,101):
# Here we can use an "if" statement to only write the number into the
# file if it is not 6. Note that in python "!=" means "not equal to"
# so the code below only executes if a is not 6
ifa!=6:
# Write the value into the file
f.write(f'{a}'+'\n')
# Close the file
f.close()
```
%% Cell type:markdown id: tags:
Again, you can check the contents of that file in your terminal by running:
`cat temp.txt`
%% Cell type:markdown id: tags:
## Done!
Well done on making it this far! As mentioned above, don't worry too much if the exact way the code is written wasn't totally clear. The following sessions will discuss in more detail exactly how to write code in python, but hopefully this has given you an idea of the kinds of basic structures used in programming that you will use in future sessions.