Python Crash course

In this notebook we will quickly go over Python at a high level. We will then go on to explore topics in more detail.

We will be creating computer programs to read, manipulate, visualize, analyze, and save air quality, atmospheric, and health data using functions that are defined in Python. Before we start with functions, however, we need to briefly touch on what data are, from the perspective of a Python program and that is rooted in the concept that in Python everything is an object.

"everything in Python is an object" (Dive Into Python)

Python programs are build from objects. Everything in Python is an object.

An object has

  1. Attributes: Attributes are data (e.g. height, weight, color (Think adjectives))
  2. Methods: Methods are functions that operate on the attributes (data) of the object (Think verbs)

The most important compoenents of the programs we will be writing are data objects and function objects. Using a biology analogy data objects are like the blood circulating through our bodies and function objects are like our organs that take blood in and return modified blood and some biological behavior.

We will briefly look at functions and then data.

What is a Function?

  • "any of a group of related actions contributing to a larger action; especially : the normal and specific contribution of a bodily part to the economy of a living organism"
  • "a computer subroutine; specifically : one that performs a calculation with variables provided by a program and supplies the program with a single result"(Merriam-Webster Dictionary)

To get a handle on what a function is in Python, let's look at some example functions from "high school" mathematics

\begin{eqnarray} y = \sqrt{x},\\ y = mx+b. \end{eqnarray}

In each of these examples, we take a value $x$ and returns a new value that we are assigning to the variable $y$.

  1. Take $x$ as input and return the square root of $x$ as output.
  2. Take $x$ as input and return $x$ multipled by $m$ plus $b$. We can generalize this pattern with the following "definition":

A "definition" of functions: A function is something that takes some kind of input and provides some sort of output

Exercise 1

Thinking this way, how would you describe each of the following as a function (what goes in and what comes out)?

  1. Lungs
  2. Radio

Functions in Python

In Python a function takes zero or more arguments (objects) and returns some object.

print

The first Python function we'll look at is print. print takes as input a string and returns as output that string "printed" to the screen. If we don't provide a string, print prints an empty string (which is nothing) to the screen.


In [ ]:
print("Hello, world")
print()
print(5+4)

In [ ]:
print("thing 1")
print("thing 1", "thing 2")
print("thing 1", "thing 2", "thing 3")

Data in Python programs

All is number.

~Pythagoras

Python has multiple data types, but the most important kinds that we will be dealing with are

  1. Numeric

    • Integers (type int). Integers are created by typing an integer (e.g. 1, 532, -4). (There is also an int function for converting (or trying to) an object to an integer.)
    • Floating point numbers (type float). Floating point numbers correspond to the real ($\mathbb{R}$) numbers and can be created by typing a decimal number (e.g. 4., 3.5, 5.4e3), by doing division (e.g. 3/4), or from the float function.
  2. Strings (for representing text) (type str). Strings are a sequence of characters and are defined by typing the characgters between single quotes (e.g. 'abc'), double quotes ("def"), or either triple single or triple double qutoes ('''ghi''',"""klm""").

Data will be either a literal or a variable. Consider the following Python statements

5+4
a=5
a+4

Example: String objects

In the cell below I'm going to create a string object named name. Because it is an object it has attributes and methods.

What is an attribute you think name might have?


In [ ]:
name = "george washington"

In [ ]:

name also has methods functions that do things to the string. One such method is capitalize.


In [ ]:
name.capitalize()

You can discover the attributes and methods of name using help(), dir(), or tab completion


In [ ]:

What are programs?

Programs are like functions:

  1. They take something as input from somewhere or something
  2. Manipulate what was input
    1. This manipulation usually makes use of conditional execution
    2. and repition
  3. Returns something new somwhere

Describe Google Docs as a Program

  1. What goes in?
  2. What manipulation occurs?
  3. What comes out?

This Jupyter notebook is a program

  1. It takes Markdown text as input and renders HTML as output
  2. It takes Python code as input and renders the relevant output, also as HTML.

Programs in Science

Computer programs are essential to modern science. They do everything from control the instruments we use (e.g. microscopes or telescopes), store the data we've collected, and help us analyze and understand the data we've collected.

We're going to use Python to write a very simple program to help us understand the relationship between weather and air quality. In later classes, we'll write programs to acquire sensor measurements from a remote computer using an application program interface (API) and explore the relationship between air quality, elevation, and wind.

Data Manipulation in Python

Given some data, whether text or numbers at this point, we can modify the value of those data or create new data from them. Here are some basic examples


In [ ]:
a_num = 5
a_num_also = 4.5

rslt = a_num + a_num_also
print(rslt)
a_num = 4 # assign a new value to a_num
print((a_num-rslt)/3)

x = int("54")
print(x)

In [ ]:
first_name = "Brian"
last_name = "Chapman"
name = first_name+last_name
print(name)
print(first_name[2])

Exercise

  1. Can you explain what is happening with first_name[2]? Why is the result 'i' not 'r'?

In [ ]:

Conditional Execution

Conditional execution involves asking true or false questions about our data and doing different things depending on the answer. These questions are in the form of

if SOME_TRUE_OR_FALSE_QUESTION: # IF THE ANSWER IS TRUE THEN WE EXECUTE THE INDENTED CODE BLOCK
    DO SOMETHING HERE
elif SOME_OTHER_TRUE_OR_FALSE_QUESTION: # elif stands for "else if"
    DO SOMETHING DIFFERENT HERE
else:
    DO SOME DEFAULT EXECUTION HERE IF ALL THE OTHER QUESTIONS WERE ANSWERED FALSE

We can have multiple elif statements and we don't have to have an else statement.

Before continuing work through this notebook on True and False

Code Blocks

Our if/elif/else example above is an example of code blocks. Python uses colons (:) and indentation to indicate code blocks: code that goes together. Code blocks will show up in many places including if/else blocks, loops, and functions.


In [ ]:
bmi = 27.3

if bmi < 18.5:
    print("underweight")
elif 18.5 <= bmi < 25:
    print("normal")
elif 25 <= bmi < 30:
    print("overweight")
elif 30 <= bmi < 35:
    print("obesity")
else:
    print("extreme obesity")

How Much to Indent?

  • Python doesn't care how much you indent as long as you are consistent
    • For that block
    • Different blocks can have different indentation
  • Indenting too little will not give much visual advantage
  • Indenting too much will not give you much space to work on a line
  • Standard indention is 4 spaces

Exercise

  1. Write an if/else code block to test if a number if non-negative

In [ ]:

Repetition in Python

There are three basic ways to repeatedly do something in Python

  1. while loops
  2. for loops
  3. recursion We will not explore recursion here.

With while loops we do something as long as a condition is true


In [ ]:
x = 0
while x < 5:
    x = x + 1 # could also write x += 1
    print(x)

With for loops we loop (iterate) over elements of a sequence, in this case a list of integers.

for loops will be our primary mechanism for iterating over data.


In [ ]:
for elem in [1, 2, 3, 4, 5]:
    print(elem)


<span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">University of Uah Data Science for Health</span> by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Brian E. Chapman</span> is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.|


In [ ]: