Python basics

Module 1

Let’s Do Digital Team

What are computers?

  • At its core, a computer is essentially a device that answers yes-no questions.
  • It answers these simple questions very very quickly.
  • By asking the computer millions of these yes-no questions, it can calculate answers to very complex questions.

How do computers think?

  • Confused by the last statement? Let me expand…
  • Computers have lots of components to enable them to work.
    • Screen to show you its output.
    • Keyboard and mouse to allow you to communicate with the computer.
    • Inside the computer’s chassis:
      • Hard drives
      • Memory sticks
      • Fans
      • Power supplies
      • Motherboards
      • Processors
  • The processor of a computer is where all of the thinking takes place.

How do computers think?

  • The processor is where these yes-no questions are undertaken.
  • The processor receives instructions in binary form.
  • Binary is basically a string of 1s and 0s (eg 01001011).
  • As modern computers communicate in binary (yes-no) form, they are said to be digital.
  • The processor reads these binary instructions.
  • Each instruction results in either a True (1) or False (0) answer (aka yes-no answer). The output (aka answer) is also in binary.

So how do we communicate with computers?

  • So computers listen, think and talk in binary.
  • We need a method to communicate with them, enabling us to get them to do what we want them to do.
  • This is where programming languages come into play.

Programming languages

  • There are over 9000 programming languages, but much less than this in routine use.
  • A programming language is written in somewhat of a human readable form (depends on the langauge).
  • Popular langauges include:
    • Javascript / typescript
    • C++
    • Go
    • Java
    • Swift
    • R
    • Python

Translation

  • When you have written your code in your favourite programming language, a software program (called the interpreter or compiler) reads your code and translates it into 1s and 0s which the computer can then read and act upon.

OK, so you can write some code. What do you put in the code? How do you tell the computer what to do?

We will be learning python

The Python programming language

  • Python is a scripting language interpreted and compiled at runtime.
  • Its syntax emphasises readability and simplicity, utilising indentation for code structuring.
  • Python supports various programming paradigms, including procedural, object-oriented, and functional.
  • With a vast standard library and active community support, Python is widely used for web development, data analysis, AI / machine learning, and automation.

Where to code?

  • There are many integrated development environments (IDEs) for the python programming language.
  • An IDE is basically a very fancy text editor where you write code, and run it (along with some other fancy stuff).
  • There are several IDEs for python, two popular ones are VS Code and Pycharm.
  • We will be using an online version of VS Code (called Codespace), so you do not need to install anything on your computer.

What is in a code?

  • You need different elements in your code to be able to tell the computer what to do. These include:
    • Variables
    • Operators
    • Expressions
    • Flow control
    • Functions
    • Error handling
    • More advanced functionalities

Variables

  • A single variable is a contained space in the computer’s memory.
  • Simple in-built variables include:
variables_simple.py
a_string = "I am a string"
an_integer = 11
a_float = 8.04
a_boolean = True

Variables

  • More complex variables include:
variables_more_complex.py
a_list = ["first element of list", "second element of list"]
another_list = [1, 5, 3, 6]
a_dictionary = {
    "1st key": "1st value",
    "2nd key": "2nd value",
}
a_tuple = (1, 2, 3, 4, 6, 7) # fixed, cannot change
a_set = {4, 2, 5, 3} # can add new items

Spaces

  • Variables names cannot have spaces, if you add a space, the computer will read this as two separate variables:
spaces.py
variable_a = "I am a variable"
variable b = "The added space will cause an error"

Syntax error:

    Cell In[1], line 2
        variable b = "The added space will cause an error"
                 ^
    SyntaxError: invalid syntax

Double or single quotation marks?

  • You will see people using ‘single’ and also “double” quotation marks.
  • It does not matter which you chose, but be consistent. If you accidentally mix pairs of quotation marks you will get strange errors.
quotation_marks.py
variable_a = "All good here with two single quotation marks"
variable_b = "I have the wrong matching quotation marks'
variable_c = 'Single quotation marks'
  • Suddenly variable_c is part of the string for variable_b and also an error!

Using both types of quotation marks

  • You can embed quotation marks within each other
quotation_marks.py
variable_a = "I want to highlight 'this' word"
variable_b = 'I would like to show you "this"'

f-strings

  • Useful to know
f_string.py
age = 25
print(f"The patient's age is : { age }")

Output

The patient's age is : 25

Add strings together

  • Or you can add strings together like this
adding_strings.py
age = 25
print("The patient's age is : " +  age)

Output

The patient's age is : 25

Indentation

  • Python is extremely sensitive to indentation. One extra space or tab in front of a line of code and you will not hear the end of it in terms of errors or strange results.
  • Indentation (in the form of tabs) of lines of code shows the computer which previous line(s) of code it relates to.

Indentation

indentation.py
if drug_prescribed == True:
    if drug_given == True:
        record_drug_given = True
        print("Drug has been prescribed and given to the patient")
    else:
        print("Drug has been prescribed but not given")
else:
    print("Drug has not been prescribed")

print("Drug round complete!")

Output (if drug has been prescribed and given)

    Drug has been prescribed and given to the patient
    Drug round complete!

Indentation

indentation.py
if drug_prescribed == True:
    if drug_given == True:
        record_drug_given = True
        print("Drug has been prescribed and given to the patient")
    else:
        print("Drug has been prescribed but not given")
else:
    print("Drug has not been prescribed")

    print("Drug round complete!")

Output (if drug has been prescribed and given)

    Drug has been prescribed and given to the patient

Naming conventions

  • There are several naming conventions for programming languages. In python, conventions are:
    • Variables, functions and methods
      • snake_case
    • Constants
      • CONSTANT_CASE
    • Classes (a higher organisation method in python)
      • CamelCase
    • Modules (a file with python code inside)
      • snake_case
    • Packages (a collection of modules)
      • lowercasepackagenames

Comments

  • Comments are useful in explaining what code is supposed to do.
  • They are essential for when you, and others, need to read your code later to problem solve or add to your code (10:1 reading to writing code ratio).
  • Use them sparingly, as they can clutter code.
  • Try and make variable and function names self explanatory.
  • You can comment with the hastag or encapsulate with triple quotation marks:
comments.py
# This is a single line comment
a_string = "a string"

""" Double quotation mark multiline comment
    Here is some more of the comment
    ALWAYS MAKE SURE YOU HAVE CLOSING TRIPLE DOUBLE QUOTATION MARKS
"""
def i_am_a_function():
    return True

''' Single quotation mark multiline comment
    Here is some more of the comment
    ALWAYS MAKE SURE YOU HAVE CLOSING TRIPLE SINGLE QUOTATION MARKS
'''
def i_am_another_function():
    return True

Comments

  • You will also come across something called docstrings. These are basically comments associated with functions / methods and classes.
  • You will see them associated with modules as well (at the top of files).
docstrings.py
def i_am_function(args1, args2):
    """A concise title

    A description of the function.

    Args:
        args1: I am the first argument to the function.
        args2: I am the second argument to the function.
    Returns:
        int: the sum of the 2 provided arguments.
    """

    x = args1 + args2
    
    return x

Basic operators

  • Operators manipulate and compare data (which are stored in variables). Operator types include:
    • Arithmetic: + - * /
    • Comparison: == > < >= <=
    • Logical: and or not
    • Assignment: = += -= *=

More advanced operators

  • These include:
    • Bitwise: & | ^ << >> ~
    • Membership: in not in
    • Identity: is is not

OK, so you can create variables, change them and compare them. What next?

Control flow - if statements

if_statement.py
patient_allergy = "amoxicillin"

if patient_allergy == "amoxicillin":
    allergy_group = "penicillins"
elif patient_allergy == "tazocin":
    allergy_group = "penicillins"
else:
    allergy_group = "not defined"

print("Patient is allergic to", allergy_group)

Output

    Patient is allergic to penicillins

Control flow - for loops

for_loop.py
list_of_numbers = [1, 2, 3, 4, 5]

for number in list_of_numbers:
    print(number)

Output

    1
    2
    3
    4
    5

Control flow - while loops

while_loop.py
count = 1

while count <= 5:
    print(count)
    count += 1

Output

    1
    2
    3
    4
    5

Colons, look out for the colons

  • All if, while and for statements must end with a colon
colon.py
count = 1

while count <= 5:
    print(count)
    count += 1

Colons

  • The same goes for functions, methods and classes
more_colons.py
def i_am_a_function():
    print("hello")
    return

Functions (and methods)

  • Blocks of reusable code that perform a specific task.
  • Help in organising code and making it more modular.
  • Part of the DRY (don't repeat yourself) philosophy.
  • A method is just a function, used within a class (a higher organisational entity in python).
  • A function:
    1. Takes zero or more input values,
    2. Undertakes some process, and
    3. Returns zero or more output values.

Functions (and methods)

  • Note the def
functions.py
def name_of_function(argument_1, argument_2):
    a_variable = argument_1 + argument_2
    return_variable = "a return value"

    print (a_variable)

    return return_variable

Functions (and methods)

functions.py
def name_of_function(argument_1, argument_2):
    a_variable = argument_1 + argument_2
    return_variable = "a return value"

    print (a_variable)

    return return_variable

Functions (and methods)

functions.py
def name_of_function(argument_1, argument_2):
    a_variable = argument_1 + argument_2
    return_variable = "a return value"

    print (a_variable)

    return return_variable

Functions (and methods)

functions.py
def name_of_function(argument_1, argument_2):
    a_variable = argument_1 + argument_2
    return_variable = "a return value"

    print (a_variable)

    return return_variable

Inbuilt functions

  • There are some functions that are already built into python, eg
built_in_functions.py
print("hello world")
print(len([0,1,2,3,4]))

Output

    hello world
    5

Other things to be aware of

  • There are several other organisational practices in python, but we will leave these for another day.
  • Just so you are aware, these are:
    • classes
    • modules
    • packages
  • There are also:
    • Some fancy syntax practices
    • Reading inputs from the terminal
    • File handling
    • Object oriented programming

Error Handling

  • Error handling is one of the most important concepts to understand and manage well. You will be spending 25-50% of your time debugging.
  • Debugging is the practice of looking for bugs (errors in the code) and trying to fix them.
  • When an error happens in python, an exception is raised. You then use the traceback to try and find the cause of the error.

Error Handling

  • If you know an error might happen at a set location, you can catch errors directly in your code:
functions.py
try:
    variable = 1 + "a"
except:
    print("I knew that you could not add an integer and a string!")
else:
    print("Somehow I did not get an error!")

Output

    I knew that you could not add an integer and a string!

The Traceback

  • At first, this looks like a very complicated output
    Traceback (most recent call last):
        File "/User/a_user/code/error_in_code.py", line 28, in <module>
            print(fruit_prices.get_price("pear"))
        File "/User/a_user/code/error_in_code.py", line 21, in get_price
            return self._price(fruit)
        File "/User/a_user/code/error_in_code.py", line 24, in _price
            return self.prices[fruit]
    KeyError: 'pear'

The Traceback

  • When reading a Traceback, alwas read from the last line upwards.
    Traceback (most recent call last):
        File "/User/a_user/code/error_in_code.py", line 28, in <module>
            print(fruit_prices.get_price("pear"))
        File "/User/a_user/code/error_in_code.py", line 21, in get_price
            return self._price(fruit)
        File "/User/a_user/code/error_in_code.py", line 24, in _price
            return self.prices[fruit]
    ==> KeyError: 'pear' <==

Compare the Traceback to the code

  • Compare against the code
functions.py
class FruitPrices:
    def __init__(self):
        # 'pear' key does not exist!
        self.prices = {"apple": 1.55, "banana": 2.44}

    def get_price(self, fruit):
        return self._price(fruit)

    def _price(self, fruit):
        return self.prices[fruit]


fruit_prices = FruitPrices()

print(fruit_prices.get_price("pear"))

You got all that?

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

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.
  • Now go have some fun in your tutor groups with hands-on coding and debugging.
  • Come back to these slides to remind yourself of key concepts - https://letsdodigital.org/learn/learn-python/module-1/