Python basics - 1st slide deck

Module 0

Let’s Do Digital Team

What are computers?

  • At its core, a computer is essentially a device that answers simple true-false questions.
  • It answers these simple questions very very quickly.
  • By asking the computer millions of these true-false 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 true-false questions are undertaken.
  • The processor receives instructions in binary form.
  • Binary is basically a string of 1s and 0s (eg 01001011).
  • A 1 can be considered True
  • A 0 can be considered False

How do computers think?

  • As modern computers communicate in binary form, they are said to be digital.
  • The processor reads these binary instructions.
  • Each instruction results in either a True (1) or False (0) output.
  • Hence, the output 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 language).
  • Popular languages include:
    • Javascript
    • 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

Python logo

The Python programming language

  • A language that is read by the computer and turned into 1s and 0s 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.

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

How is code read by the computer?

  • All code is read sequentially, one line after another.
reading_code.py
print("I am the first line of code read by the computer")
print("I am the second line read by the computer")
print("Guess what, I am the third line read by the computer")

Output

    I am the first line of code read by the computer
    I am the second line read by the computer
    Guess what, I am the third line read by the computer

How is code read by the computer?

  • This might make your head spin.
reading_code.py
def i_am_a_function():
    print("I am a line inside a function")

print("I am printed first")
i_am_a_function()

Output

    I am printed first
    I am a line inside a function

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",
}

Variables & memory

  • Variables are stored in the computer’s memory (RAM).
  • Memory - think of it as a parking garage with a huge number of parking spaces.
  • Python manages memory for you (creating, reading, updating, and destroying).

Variables - indexing / key

  • You can get a value from a list or dictionary by indexing or specifying a key, respectively:
index_keys.py
a_list = ['a', 'b','c', 'd']

a_dictionary = {
    "1st key": "1st value",
    "2nd key": "2nd value",
}

print(a_list[0])
print(a_dictionary["1st key"])

Output:

    a
    1st value

Variables - zero indexing

  • Note: lists are zero indexed
index_keys.py
a_list = ['a', 'b','c', 'd']

print(a_list[0])

Output:

    a

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 double quotation marks"
variable_b = "I have the wrong matching quotation marks'
variable_c = 'Single quotation marks'

Output

    File "file_with_bad_code.py", line 2
    variable_b = "I have the wrong matching quotation marks'
             ^
    SyntaxError: unterminated string literal (detected at line 18)
  • variable_b’s string causes an error due to unmatching quotation marks.

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

Add strings together

  • You can add strings together as below
  • Note, you cannot add an integer to a string in python
adding_strings.py
age = "25"
print("The patient's age is: " +  age)

Output

    The patient's age is: 25

Use a comma

  • Or you can use as separate arguments
using_commas.py
age = 25
print("The patient's age is:",  age)

Output

    The patient's age is: 25
  • Note, the print statement when used like this adds a space between the arguments in the print out.

f-strings

  • A more advanced, but powerful method.
f_string.py
age = 25
print(f"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.
  • In standard Codespace, 1 tab = 4 spaces

Indentation

  • Let’s say a drug has been prescribed and given
indentation.py
if drug_prescribed == True:
    if 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

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

Indentation

  • Let’s say a drug has been prescribed and given
indentation.py
if drug_prescribed == True:
    if 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

    Drug has been prescribed and given to the patient

Naming conventions

  • There are several naming conventions in python. The convention you need to know about for this module is:
    • snake_case - for variables, functions and methods

What is in a code?

  • You may notice that you can enter values for a variable (and other things) over several lines. This is allowed, but we will not bog you down with the specifics for now.
human_organs.py
human_organ_locations = {
    "heart": "chest", 
    "stomach": "abdomen", 
    "brain": "head"
}

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 are lines of code not translated by the interpretor.

Comments

comments.py
# This is a single line comment

Comments

comments.py
""" Double quotation mark multiline comment
    Here is some more of the comment
    ALWAYS MAKE SURE YOU HAVE CLOSING TRIPLE DOUBLE QUOTATION MARKS
"""

Comment

comments.py
''' Single quotation mark multiline comment
    Here is some more of the comment
    ALWAYS MAKE SURE YOU HAVE CLOSING TRIPLE SINGLE QUOTATION MARKS
'''

To uncomment

  • To uncomment - remove the hashtag, or triple single / double quotation marks.
comments.py
# i_am_commented_out_function_call()

i_am_a_function_call_that_can_run()

Basic operators

  • Operators manipulate and compare data (which are stored in variables). Operator types include:

  • Assign =

    x = "a string"

Basic operators

  • Arithmetic:
    • + plus (eg x = 3 + 5)
    • - minus
    • * multiply
    • / divide

Basic operators

  • Comparison:
    • == compare (eg if x == 8)
    • > greater than
    • < less than

More advanced operators

  • Membership: in not in
membership.py
    a_list = [1,2,3,4,5]

    if 2 in a_list:
        print("Yes, 2 is in the list")

Output

    Yes, 2 is in the list

Functions

  • Blocks of reusable code that perform a specific task.
  • Help in organising code and making it more modular (code can be reused).
  • Part of the DRY (don't repeat yourself) philosophy.

Anatomy of a function

functions.py

def name_of_function(argument_1, argument_2):

    print(argument_1 + argument_2)

    return "Finished"

Anatomy of a function

functions.py

def name_of_function(argument_1, argument_2):

    print(argument_1 + argument_2)

    return "Finished"

Anatomy of a function

functions.py

def name_of_function(argument_1, argument_2):

    print(argument_1 + argument_2)

    return "Finished"

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

Errors

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, ones says an exception is raised. You then use the traceback to try and find the cause of the error.

The Traceback

  • At first, this looks like a very complicated output

  • The traceback is printed to the terminal, as such:

      Traceback (most recent call last):
          File "/User/a_user/code/error_in_code.py", line 7, in _price
              print(human_organ_locations["football"])
      KeyError: 'football'

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 7, in _price
              print(human_organ_locations["football"])

    ==> KeyError: ‘football’ <==

Compare the Traceback to the code

  • Compare against the code
human_organs.py
human_organ_locations = {
    "heart": "chest", 
    "stomach": "abdomen", 
    "brain": "head"
}

print(human_organ_locations["football"])

Traceback

  • Sometimes the traceback will underline erroneous code with upwards arrows ^

Syntax error:

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

Squiggly lines

  • Hint: Codespace will underline with squiggly lines to highlight errors.
Squiggly lines under errors in python code

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 2.
  • You need to change directory
$ cd lesson_2
  • Then run the first exercise:
$ python exercise_1.py

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 your code. 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-0/