Wayne's Github Page

A place to learn about statistics

Interacting with Python

Basic programming is about writing instructions for the computer to execute tasks like reading in some data. Here we will write these instructions in Python. Before you can assign instructions though, there are some key things to know first.

Some basics about folder structure

You need to know the “location” of

All files (data or programs) are organized by folders (e.g. Downloads vs Documents vs Desktop) on modern operating systems (e.g. MacOS and Windows). Most beginners encounter problems with instructions like “read in this file” because Python has a different understanding of where “this data” is referring to. The folder where Python assumes you’re working from is called the “working directory”.

Another important topic is “permissions” related to these files if you are encountering further problems. Ask a TA or Google online to learn more about permissions.

The different modes of working with Python

Python enables one to issue instructions to the computer, these are often referred to as “commands”. You’ll write instructions called code, that Python can interpret into commands for the computer to execute.

To interact with Python, there are several different modes that we list below:

Interacting with the REPL

The read-evaluate-print loop (REPL) is the interface that responds to every command you type immediately.

The REPL is most commonly found by executing python in the command line. You can directly type code into the REPL, i.e. the space after >>>.

REPL demo

Flaws:

Pros:

Writing script then executing them

This is the most common coding pattern for software development (not true for data analysis). You write your code into a script, e.g. save the following into a file called demo.py then execute the commands by passing the script to Python for interpretation, e.g. typing python demo.py into your command line in the directory where demo.py is located.

# demo.py

print(1 + 1)
print(1 + 2)

Your code will be executed from top to bottom in order. Notice that the code writing and code execution are two separate steps.

Flaws:

Pros:

Notebooks (in between REPL and scripts)

Notebooks allow you to write “blocks” of code as in a script without executing them, then you can choose to run the code in different blocks individually or together.

Flaws

Pros