Python

Module 1

Let’s Do Digital Team

We will be using Python

Python logo

The Python programming language

  • A programming language interpreted and compiled at runtime.
  • Its syntax emphasises readability and simplicity.
  • It utilising indentation for code structuring.
  • Widely used for web development, data analysis, AI / machine learning, and automation.

Reminder of the basics

A function

a_function.py
def a_function_that_prints(something_to_print):
    print(something_to_print)
    return

a_function_that_prints("Hello World!")
a_function_that_prints("Woo Hoo!")

Output

    Hello World!
    Woo Hoo!

Error handling

  • You can raise errors with raise
raise_error.py
raise_error = True

if raise_error == True:
    raise ValueError("An error has been raised!")
  • Other types include:

      TypeError
      ZeroDivisionError
      FileNotFoundError
      IndexError
      KeyError

Handling potential exceptions

exception.py
try:
    number = int("!")
    print("Conversion successful!")
except ValueError:
    print("Conversion failed. Please enter a valid number.")
else:
    print("The number is:", number)

Output

    Conversion failed. Please enter a valid number.

Class, please sit down!

Classes

  • Much like functions are used to simplify reusable code, classes are used to organise code at a higher level.
  • Classes are used to store attributes and actions of real life objects.

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()

Naming conventions

  • Variables, functions and methods
    • snake_case
  • Classes
    • CamelCase

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()

Creating an instance of the class

patient_1_vitals = VitalSigns(37.5, 80)

  • This line of code creates an instance of the VitalSigns class.
  • Essentially you have created a VitalSigns object.
  • Classes are an example of object oriented programming.

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()
  • When you create an instance of a class (aka object) the __init__ method is automatically called.
  • Remember, a method is just a function inside a class.

Creating an instance of the class

classes.py
patient_1_vitals = VitalSigns(37.5, 80)
  • You have passed 37.5 and 80 as arguments.

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()
  • 37.5 is set as the temperature argument.
  • 80 is set as the heart_rate argument.

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()

One needs to know oneself

  • self refers to the instance of the class that you have just created, eg patient_1_vitals.
  • self allows the object you have created to keep track of its own data.
  • self is ALWAYS passed as an argument to methods of a class.
  • self is ALWAYS the first argument to methods in a class.

Anatomy of a class

classes.py

class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate
    
    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")

patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()

The dot operator

patient_1_vitals.display()

  • It may look strange, but the . (dot) in between patient_1_vitals and display() is basically just a way to get data or use a method of a class.

  • So in the instance above, you are basically saying:

    “For the patient_1_vitals instance that I have created, please run the display() method.”

  • Remember, a method is just a function inside a class.

The final output


class VitalSigns:
    def __init__(self, temperature, heart_rate):
        self.temperature = temperature
        self.heart_rate = heart_rate

    def display(self):
        print(f"Temperature: {self.temperature}°C")
        print(f"Heart Rate: {self.heart_rate} bpm")


patient_1_vitals = VitalSigns(37.5, 80)

patient_1_vitals.display()

Output:

    Temperature: 37.5°C
    Heart Rate: 80 bpm

Libraries

Libraries

  • Libraries are amazing. They will save you a lot of time and effort.
  • Libraries are basically a collection of organised code that someone else (usually a group of people) has already written.
  • You can use the functionality in these libraries within your own code.

Safety

  • Of course, not every library is created equally. Some libraries are written better than others.
  • This is very important to realise when you are looking to get consistent functionality from a library.
  • Hence, choosing the wrong library, which could be poorly written, could affect patient care.
  • We will talk about safety and code in future modules.

Installing libraries

  • This is very easy, just use pip
$ pip install streamlit

Preinstalled libraries

  • There are a large collection of preinstalled libraries in python, so you will not need to use pip to install them.

  • eg

      os
      random
      datetime
      math
      json

Modules

  • Modules are collections of code, which can be part of higher organisation levels, for example libraries.
  • Hence, you can think of a module as a single book in a physical library.

Importing modules

  • People say “import that library”.
  • In fact, they are importing a module.
import.py

import datetime

now = datetime.datetime.now()

print(now)

Importing modules

import.py
import datetime

now = datetime.datetime.now()

print(now)
  • You use the dot operator to access the sub-modules, classes, methods and attributes within the imported module.

How to write

  • It might seem daunting to write code, and you might be wondering where to start.
  • The best way to write code is to just write it.
  • Think a little about what you are going to write, but then write down a line of code and run the code. If it work, great! If it did not work, great too! Either way you have learnt something.

You got all that?

  • Now it is your turn.
  • Time for some hands on coding in Lesson 1.

Computers are pedantic!

  • Remember that computers think in True and False, e.g. 1 and 0s. They are literal thinkers.
  • Even one character being out of place can break an entire code base. So watch out for that unpaired quotation mark, look out for that space that should not be there, and make sure you match your indentations to your if statements.
  • Come back to these slides to remind yourself of key concepts - https://letsdodigital.org/learn/learn-python/module-1/

Lesson 1

  • Make sure you have a GitHub account.
  • Join your tutor group in the named Zoom break out rooms.
  • Go to the page at https://github.com/letsdodigital/coding-hands-on
  • Click on the <> Code button and then the Codespaces tab.
  • Click on Create codespace on main

Break out room button

Screen shot of break out room button in Zoom

Codespace load

Screen shot of github webpage with arrows showing how to start Codespace

Ignore this

  • Ignore the pop out about extensions you may get in the bottom right of Codespace

Get to your first lesson

  • Change the directory (don’t type the $. This is just how we show this is the command line):
    $ cd programming_in_healthcare/module_1/lesson_1
  • And then
    $ python exercise_1.py
  • Did it work? If so, open up the exercise_1.py file.
  • Any problems, just ask your tutor for help.
  • There is no such thing as a stupid question, only the question left unanswered.
  • We will give you 20 minutes for lesson 1.