Welcome 👋¶

KD4014 Programming with Python¶

Please sit in pairs ¶

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
  • Python programing and Software Sustainability
  • PhD in Materials Science / MSci in Theoretical Physics

Course outline¶

  • Week One: Python basics (variables, data types, for loops, conditionals, functions)
  • Week Two: Data analysis and plotting
  • Assessment: Coursework will be handed out at the end of the last lab. Due in 16th December.

...but why is programming important?

Why Programming? Reproducibility¶

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: jobs are expected to increase by 21% by 2028
  • 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.

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 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¶

Task one: questionnaire¶

Find the link on the course website: lucydot.github.io/python_novice¶

Task two: 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

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 ToDo list with heading "ToDo list"

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

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]

✨ Lesson Outline ✨¶

  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

✨ Previous Lesson ✨¶

  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

✨ Today's Lesson ✨¶

  1. For loops
  2. Conditionals
  3. Writing functions
  4. Variable scope
  5. Libraries

For Loops¶

For Loops¶

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

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

Pairs 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 ____

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

✨ Last week ✨¶

  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

✨ This week ✨¶

  1. Programming good practice
  2. Python Scientific libraries
  3. Reading and cleaning data with NumPy:
  4. Analysing Data with NumPy:
  5. Visualising Data with Matplotlib:
  6. Assessment:

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

Python scientific libraries¶

Pairs 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¶

Pairs task (5 min)¶

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

✨ Lesson outline ✨¶

  1. Programming good practice: docstrings, numpy.__version__, variable names, assert statements
  2. Python Scientific libraries: import matplotlib.pyplot as plt
  3. Reading (and cleaning) data with NumPy: numpy.loadtxt(), ndarray, numpy.savetxt
  4. Analysing Data with NumPy: mean, min, max
  5. Visualising Data with Matplotlib: plot(), xlabel(), ylabel(), savefig()

Next steps¶

This is just the beginning

You will meet Python again in future years (including KD5081).

You could also...

  • Follow up with an online tutorial (e.g. here)
  • Adapt what we have done here to create a notebook/script for your own mini-project
  • Take part in the Advent of Code