Welcome 👋¶

Programming with Python¶

Dr Lucy Whalley / l.whalley@northumbria.ac.uk.

Course website: lucydot.github.io/python_novice

Who am I?¶

  • Computational Materials Scientist: Physics, Chemistry, Software Engineering
  • Renewable Energy materials: Solar cells, batteries
  • Software development and sustainability
  • PhD in Materials Science / MSci in Theoretical Physics

Who are you?¶

Pre-course questionnaire: https://bit.ly/python-31Jan

Course outline¶

  • Session 1: Getting started (Installation, Jupyter Notebooks, variables, data types)
  • Session 2: Python basics (for loops, conditionals, functions)
  • Session 3: Using Python libraries to read and analyse data
  • Session 4: Using Python libraries to plot data

Your thoughts?? 🤔

Why Programming? Computational Physics¶

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.

Why Programming? Better Science¶

For the findings of a study to be reproducible means that results obtained by an experiment or an observational study or in a statistical analysis of a data set should be achieved again with a high degree of reliability when the study is replicated.

Why Programming? Employability¶

  • The software development job market is growing fast:

    Tech and IT-related job vacancies now make up 12% of all open UK job vacancies

  • The data skills gap:

    Almost half of businesses (48%) are recruiting for roles that require hard data skills but under half (46%) have struggled to recruit for these roles over the last 2 years.

  • The focus of this workshop is to equip with you with some of the transferable skills needed for success in a range of computational applications.

Why Python? The trade-off¶

Why Python? It gives you wings¶

Why Python?¶

  • readable
  • free to use
  • cross-platform
  • well documented
  • widely used

Warning: Programming can be frustrating...¶

In programming, the little things matter! An extra full-stop or the smallest typo will stop your code running

...pair programming helps...¶

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)

...The stickies will help also¶

Computer setup¶

Open up a Jupyter Notebook:¶

- If using a lab computer, use your OneDrive folder
- If using a laptop, follow the setup instructions here: lucydot.github.io/python_novice
- Green Sticky once you are done

Task complete? Explore the course website.¶

✨ Lesson Outline ✨¶

  1. Running python code
  2. Variables
  3. Data types
  4. Functions, help and errors
  5. Lists

Plain text vs. Jupyter Notebook¶

  • Plain text approach:
    • write code in a text editor
    • save with a .py extension
    • run code using a terminal
  • Jupyter notebook approach:
    • write code in a jupyter notebook
    • run code in a jupyter notebook
    • save with a .ipynb extension

Pairs task (5 min)¶

Use your Jupyter notebook to...

  • link to your favourite webpage
  • calculate 3624357/325
  • make a bullet pointed to-do list with heading "to-do list"
  • display a picture, e.g. http://bit.ly/python_cat

Pairs task (2 min)¶

Can you predict what the final value of position is for the code block below?

initial = 'left'
position = initial
initial = 'right'

Data types¶

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

Pairs task (2 min)¶

Which of the following will print 2.0?

first = 1.0
second = "1"
third = "1.1"
  1. first + float(second)
  2. float(second) + float(third)
  3. first + int(third)
  4. first + int(float(third))
  5. int(first) + int(float(third))
  6. 2.0 * second

Welcome 👋¶

Programming with Python¶

Dr Lucy Whalley / l.whalley@northumbria.ac.uk.

Course website: lucydot.github.io/python_novice

✨ Previously... ✨¶

  1. running python code: Jupyter Notebooks, markdown basics
  2. variables: variable names, variable assignment, print(), execution order
  3. data types: integer, float, string, list, len(), string operations/indexing/slicing, type conversion: int(), str(), float()

✨Today... ✨¶

  1. Functions, help and errors
  2. Lists
  3. For loops
  4. Conditionals
  5. Writing functions
  6. Variable scope

Lists¶

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]

For Loops¶

For Loops¶

Task (3 min)¶

I want to sum the integers from 1 to 10. What is wrong with this code? How can I fix it?

total = 0
for number in range(10)
    total = total + number
print(total)

Conditionals¶

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')

Task (3 min)¶

What is wrong with the code? 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")

Functions¶

def print_greeting():
    print ("Hello!")

Functions¶

def print_personalised_greeting(name):
    print ("Hello "+name)

✨ Summary so far ✨¶

  1. running python code: Jupyter Notebooks, markdown basics
  2. variables: variable names, variable assignment, print(), execution order
  3. data types: integer, float, string, list, len(), string operations/indexing/slicing, type conversion: int(), str(), float()
  4. functions, help and errors: min(), max(), round(), help(), runtime errors (exceptions), syntax errors
  5. lists: sequence type, immutable vs mutable, list method append, del
  6. For loops: dummy variable, loop syntax, index from 0
  7. Conditionals: if, elif, else, ordering
  8. Writing functions: function syntax, return statement, parameters and arguments

Task (2 min)¶

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 ____

✨ Today... ✨¶

Course website: https://lucydot.github.io/python_novice/

  1. Variable scope
  2. Programming good practice
  3. Python Scientific libraries
  4. Numpy arrays for storing data
  5. Selecting data from Numpy arrays
  6. Visualising data with Matplotlib

Variable Scope¶

pressure = 103.9

def adjust(temperature):
    new_temperature = temperature*1.43/pressure

Variable Scope¶

pressure = 103.9

def adjust(temperature):
    new_temperature = temperature*1.43/pressure
    return new_temperature

⚠️ Programming good practice ⚠️¶

Document your code with docstrings

 def calc_bulk_density(mass,volume):
     density = mass / volume
     return density

⚠️ Programming good practice ⚠️¶

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?

⚠️ Programming good practice ⚠️¶

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

⚠️ Programming good practice ⚠️¶

Focus on readability

  • consistency is key
  • whitespace (see the PEP8 style guide):
    spam(ham[1], {eggs: 2})
    spam( ham[ 1 ], { eggs: 2} )
  • clear, meaningful variable names (don't just use x, p etc and expect the reader to know what they mean!)

⚠️ Programming good practice ⚠️¶

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__)

Task (5 min)¶

  • Write a function to calculate the area of a triangle.
  • Document your function with a docstring.
  • Write an assert statement to test that the function inputs are sensible.

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

Python scientific libraries¶

Task (15 min)¶

You want to select a random character from a string. base = "ATCHAGHRASG"

  1. which standard library module could help you?
  2. which function could you select from that module?
  3. try to write a program that uses that function

Feel free to look online (search for "Python standard library")

Indexing NumPy arrays¶

Task (5 min)¶

Decipher the message below using the following array which has the variable name Cipher (note that you do not need to write any code to complete this exercise).

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])

✨ Today's summary... ✨¶

  1. Variable scope: local and global variables
  2. Programming good practice: docstrings, numpy.__version__, variable names, assert statements
  3. Python Scientific libraries: import numpy, import numpy as np
  4. Numpy arrays for storing data: numpy.loadtxt(), array attributes, numpy.savetxt(), numpy.zeros
  5. Selecting data from Numpy arrays: indexing and slicing arrays,
  6. Visualising data with Matplotlib: plt.plot, plt.legend(),plt.title(), plt.xlabel(), figures and sub-plots

✨ Today... ✨¶

Course website: https://lucydot.github.io/python_novice/

  1. Visualising Data with Matplotlib
  2. Analysing data with Numpy
  3. Writing Python scripts
  4. Feedback

✨ Full workshop summary.. ✨¶

  1. running python code: Jupyter Notebooks, markdown basics
  2. variables: variable names, variable assignment, print(), execution order
  3. data types: integer, float, string, list, len(), string operations/indexing/slicing, type conversion: int(), str(), float()
  4. functions, help and errors: min(), max(), round(), help(), runtime errors (exceptions), syntax errors
  5. lists: sequence type, immutable vs mutable, list method append, del
  6. For loops: dummy variable, loop syntax, index from 0
  7. Conditionals: if, elif, else, ordering
  8. Writing functions: function syntax, return statement, parameters and arguments
  9. Variable scope: local and global variables
  10. Programming good practice: docstrings, numpy.__version__, variable names, assert statements
  11. Python Scientific libraries: import matplotlib.pyplot as plt
  12. Reading (and cleaning) data with NumPy: numpy.loadtxt(), ndarray, numpy.savetxt
  13. Analysing Data with NumPy: mean, min, max
  14. Visualising Data with Matplotlib: plot(), xlabel(), ylabel(), savefig()

Next steps¶

This is just the beginning

You could...

  • Use Python to analyse and plot your own data
  • Make your own Github website to publicise your skills (not Python but a good skill to have!)
  • Explore a nice example of using Jupyter Notebooks: https://assessingsolar.org/intro.html
  • Follow up with a Python online tutorial (e.g. here)
  • Take part in the Advent of Code