Dr Lucy Whalley / l.whalley@northumbria.ac.uk.
Part One: Getting started (Jupyter Notebooks)
Part Two: Python basics - data types, for loops, functions...
Part Three: Data arrays with Numpy
Part Four: Plotting with Matplotlib
Website: lucydot.github.io/python_novice
Computer labs: Are important! Let me know if you cannot attend. Register will be kept. Will aim for 90 minute sessions.
Office hours: Tuesday 4-5pm.
Coursework will be handed out 21st November, to be returned 20th December.
Must be done individually
Must be submitted as a Jupyter Notebook.
Computational physics encompasses areas including materials modelling, particle physics simulations, protein structure prediction and plasma modelling. In fact, it is possible to find a computational branch for every major field in physics.
The focus of this course is to equip with you with some of the transferable skills needed for success in a range of computational disciplines, with examples tailored towards the physics domain.
Digital skills are no longer limited to tech and online roles, but are now nearly-universal requirements across all sectors and skill levels today (UK Government)
The demand for software developers is big, and it pays well – really well! (Just IT)
There's a lot of promise in quantum computing, but companies first need to figure out how they can attract more people into the industry. (Owen Hughes, Zdnet)
In programming, the little things matter! An extra full-stop or the smallest typo will stop your code running
Betty Snyder and I, from the beginning, were a pair. And I believe that the best programs and designs are done by pairs, because you can criticise each other, and find each others errors, and use the best ideas. Jean Bartik, Electronic Numerical Integrator and Computer (developed in 1945)
- If using a lab computer
- login to OneDrive
- search for "Jupyter Notebook"
- navigate to your OneDrive and create a KD4014 folder
- If using a laptop, follow the setup instructions here: lucydot.github.io/python_novice
.py
extension.ipynb
extensionUse your Jupyter notebook to...
A. Can you predict what the final value of position
is for the code block below?
initial = 'left'
position = initial
initial = 'right'
B. What is a better variable name: m
, min
or minutes
?
Data type | Python name | Definition | Example |
---|---|---|---|
integer | int | positive or negative whole numbers | -256 |
float | float | real number | -3.16436 |
string | str | character string | "20 pence." |
list | list | a sequence of values | ['frog',2,8] |
+ boolean, dict, tuple, complex, None, set
A. Which of the following will print 2.0?
first = 1.0
second = "1"
third = "1.1"
first + float(second)
float(second) + float(third)
first + int(third)
first + int(float(third))
int(first) + int(float(third))
2.0 * second
B. Write an expression to calculate $s=ut+\frac{1}{2}at^2$
Explain in simple terms the order of operations in the following program: when does the addition happen, when does the subtraction happen, when is each function called, etc.
What is the final value of radiance
?
radiance = 1.0
radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5))
Data type | Python name | Definition | Example |
---|---|---|---|
integer | int | positive or negative whole numbers | -256 |
float | float | real number | -3.16436 |
string | str | character string | "20 pence." |
list | list | a sequence of values | ['frog',2,8] |
old
from gold
values = ____
values.____(1)
values.____(3)
values.____(5)
print('first time:', values)
values = values[____]
print('second time:', values)
first time: [1, 3, 5]
second time: [3, 5]
Reorder and properly indent the lines of code below
so that they print an array with the cumulative sum of data
.
The result should be [1, 3, 5, 10]
.
cumulative += [sum]
for number in data:
cumulative = []
sum += number
sum = 0
print(cumulative)
data = [1,2,2,5]
mass = 4.2
if mass > 3:
print(mass, ' is large')
if mass < 2:
print(mass, ' is small')
if 2 <= mass <= 3:
print(mass, ' is just right')
Students with more than 90 should be awarded an A, more than 80 awarded a B and more than 70 awarded a C. What is wrong with the code below? Fix the code so that it works as intended
grade = 95
if grade >= 70:
print("grade is C")
elif grade >= 80:
print("grade is B")
elif grade >= 90:
print("grade is A")
def print_greeting():
print ("Hello!")
def print_personalised_greeting(name):
print ("Hello "+name)
Fill in the blanks to create a function that takes a list of numbers as an argument and returns the first negative value in the list
def first_negative(values):
for v in ____:
if ____:
return ____
pressure = 103.9
def adjust(temperature):
new_temperature = temperature*1.43/pressure
pressure = 103.9
def adjust(temperature):
new_temperature = temperature*1.43/pressure
return new_temperature
Document your code with docstrings
def calc_bulk_density(mass,volume):
density = mass / volume
return density
Document your code with docstrings
def calc_bulk_density(mass,volume):
"Return dry bulk density = powder mass / powder volume."
density = mass / volume
return density
What are the other two types of code documentation you can use?
Test your code
def calc_bulk_density(mass,volume):
"Return dry bulk density = powder mass / powder volume."
assert mass > 0, "mass must be more than zero"
assert volume > 0, "volume must be more than zero"
density = mass / volume
return density
Focus on readability
spam(ham[1], {eggs: 2})
spam( ham[ 1 ], { eggs: 2} )
x
, p
etc and expect the reader to know what they mean!)def triangle_area(base,height):
"""returns the area A of a triangle using the formula A=0.5*b*h,
where b is the base and h is the height."""
assert base > 0 and height > 0, "negative lengths are not allowed"
return 0.5*base*height
import math
import numpy
sping_constant = [3.1,7.2,2.7]
for x,y in enumerate(sping_constant):
mass = 10
k=y
print("The angular frqency is", numpy.sqrt(k/mass))
You want to select a random character from a string. base = "ATCHAGHRASG"
Feel free to look online (search for "Python standard library")
Think about reproducibility
Reproducibility is more complex and difficult than you might think..
One straight-forward thing you can do is print the version number for each package you import using print(packagename.__version__)
Crack the code using the following array which has the variable name Cipher
:
Cipher[0,1],Cipher[1,0],Cipher[2,1]*2,Cipher[1,1]
Cipher[0,2],Cipher[1,1],Cipher[2,0],Cipher[2,1],Cipher[1,2])
This is just the beginning
You will meet Python again in future years (including KD5081).
You could also...