Python 101 - Getting started with Python

ENV 859 - Geospatial Data Analytics   |   Fall 2023   |   Instructor: John Fay  

Introduction

After familiarizing ourselves with what Python is and setting up our Jupyter notebook environment in the last session, we’re now ready to actually begin learning Python. We will follow the scheme laid forth in the VanderPlas book (and by many others) by beginning with the elements of basic Python syntax, the rules of writing code as it were. From there, we’ll cover the basic building blocks of writing code: variables and coding objects such as integers, floating point numbers, strings and Booleans, and how we control them with code using items such as “operators”, “methods”, and “functions”.

The lessons presented here closely follow topics presented in Jake VanderPlas’ book A Whirlwind Tour of Python (“WToP”). This is an excellent, interactive resource (notes below on how to obtain it). Rather than repeating the points made in the book, I provide here a bullet list of the key concepts you should take away from each section. As a class, we’ll walk through examples and clarify the more nuanced points.

To complete these lessons, you will need a machine with Python and Jupyter Notebooks installed. This includes any machine in which ArcGIS Pro is installed. If you do not have access to that, contact me and I can show you how to set up a “virtual container”. That will allow you to forge head.

Before commencing, it’s useful to note that learning a coding language is an ongoing, iterative process. It’s ok to not understand everything that’s going on. For some things, you’ll simply have to take a leap of faith how it works – for now. However, do feed your curiosity at this time. Always seek to play and experiment; you can most likely get reset things if you get too far off course. But experimentation and continual practice is where most of the learning takes place.


Learning Objectives

Topics Learning Objectives
Lesson prep Download GitHub repository files to your local machine.
1. Basic Python Syntax List the basic elements of Python syntax
Use comments in scripts and describe how they are useful
Write multiple Python statements on a single line
Write a single Python statements spanning multiple lines
Explain what “whitespace” is and its significance in Python
Explain how indentation is used with respect to code blocks
Explain how colons are used with respect to code blocks
2. Variables & Objects Define and use variables in Python
Reveal the value of a variable with print()
Reveal the data type of a variable with type()
Explain the concept of data type and its importance in Python
Locate documentation for Python objects
3. Operators Describe the different types of Python operators
Use Python as a calculator with arithmetic operators
Incrementally change a variables value with assignment operators
Compare values of two objects using comparison and Boolean operators
Describe the different between object identity & equality
Use Python’s membership operators to determine membership
4. Simple Values/Scalars List Python’s simple data objects and provide examples of each
Explain the difference between a short vs. long integer
Create floating point numbers using decimal and exponential notation
Create & manipulate string objects via their methods
Describe when and where the None Type object might be used
List the various object values that correspond to Boolean “False” values
Coerce or cast variables from one data type into another

Lesson prep

This session follows the structure of VanderPlas’ 2016 edition of Whirlwind Tour of Python (“WWToP”), which is not only an excellent resource for learning Python, but is also free and accessible in many formats. Links to various formats of the book are below and we will actually nab our own copy as part of this set of exercises.

A. Download A Whirlwind Tour of Python to your class drive

We’ll begin by downloading some Jupyter Notebooks (including VanderPlas’ entire WWToP book!) with detailed description and code examples on various topics. The text below serves as a road map of what we’ll cover, including links to the more detailed material and a list of the key concept in each lesson Here’s how:

  • In your class folder (e.g. your “V:” drive) create a new folder named Python101 to hold all the lesson materials.
  • Open your web browser to the book’s GitHub repository:
    https://github.com/jakevdp/WhirlwindTourOfPython
  • Find the green button labeled ↓ Code. Expand the menu and select Download Zip.
    Save the Zip file to the Python101 folder created in the first step.
    • → If downloading from the GitHub site fails, you can just click this link to download it directly.
  • Unpack the zip file contents into its own folder within the Python101 folder.
    You should now see a number of notebook (.ipynb) files (and some others) in this folder.

B. Download the class exercises to your class drive

In addition to VanderPlas’ book, I’ve created a number of Python exercise files for you to download. These exercises will help reinforce the concepts learned.

  • Navigate to https://github.com/ENV859/PythonExercises.
  • Download the repository into your Python101 folder as you did above.
    • → Again, if you run into issues getting the file, it is linked here.
  • Unpack the zip file contents into its own folder within the Python101 folder.

C. Open the notebooks in Jupyter

Finally, we’ll open these notebooks in Jupyter Notebooks.

  • Find the Jupyter shortcut file (*.lnk) created in the last section and copy it to your Python101 folder. Use it to start the Jupyter Notebooks application.
  • Alternatively, open a new Python Command Prompt. In this prompt, navigate to your V: drive and type jupyter notebooks to start the app.

We will now use VanderPlas’ Whirlwind Tour of Python as a guide to introduce ourselves to the fundamentals of Python. Links are provided below with summaries of what is covered and a list of the related exercises. Each section is reviewed in the accompanying videos. Exercises are provided to reinforce the concepts discussed.


:point_right: Alternate forms of VanderPlas’ Whirlwind Tour of Python:

1. Basic Python Syntax

Reading : WToP: 02-Basic-Python-Syntax.ipynb

Key concepts:

  • Python is designed to be readable: can you understand the code on the page?
  • What are “comments” in a script and how are they used?
  • What indicates the separation two python statements?
  • How is line indentation (or “whitespace”) used in Python coding?
  • How are colons used?
  • How are parentheses used?

Exercises:

  • 1a thru 1e in PythonExercises1.ipynb

2. Basic Python Semantics: Variables and Objects

Reading : WToP: 03-Semantics-Variables.ipynb

Key concepts:

  • Python is an “object oriented” programming language, and what that means.
  • Variables are labels we associate with (or “point to”) an object, done so using =.
  • Mutable vs immutable objects and how they affect assignment.
  • When assigned, a variable inherits the data type of the object to which it is assigned. (“Dynamic typing”)
  • We can see the data type of a variable using the type() command.
  • :point_right: We can also get help on an object via help() or in Jupyter by putting a ? before the variable :point_left: :
myName = "john"
help(myName)
?(myName)
?(myName.upper)

Exercises:

  • 2a thru 2c in PythonExercises1.ipynb

3. Basic Python Semantics: Operators

Reading : WToP: 04-Semantics-Operators.ipynb

Key concepts:

  • How to use Python as a calculator
    • Addition, subtraction, multiplication, division (true and floor)
    • Modulus
    • Exponentiation (powers)
  • Bitwise operations (we’ll skip this for now…)
  • Assignment operations
    • Assigning and re-assigning values with =
    • Augmented assignment values: +=, -=, *=, */,…
  • Comparison operations
    • returns a Boolean
    • is equal to, is greater than…: ‘==, >,>-,!=
  • Comparison (aka “Boolean”) operations
    • and, or, not
    • Boolean vs bitwise
  • Identity and membership operators
    • is infers object identity, not equality; two variables can be equal, but not the same object
      • If x is y is true, then changing one will change the other
    • in checks for membership

Exercises:

  • 3a thru 3c in PythonExercises1.ipynb

4. Built-In Types: Simple Values/Scalars

Reading : WToP: 05-Built-in-Scalar-Types.ipynb

Key concepts:

  • Integers
    • “fixed” vs “variable” precision (short, long)
      • a = 2; type(a) -> ‘int’
      • b = 2 ** 250; type(b) –> ‘long’
    • Integer division, v2 vs v3…
  • Floating-point numbers
    • standard vs decimal notation
    • floating point precision gotcha
  • Complex (not for us…)
  • Strings
    • Use of single and double quotation marks.
    • string functions (Jupyter’s tab completion)
    • Concatenating strings
    • String indexing and slicing (to be continued…)
    • Use of Python’s escaping character: “\” (Not in VanderPlas)
  • The None object
  • Booleans
    • Deriving vs creating
    • True and False keywords
    • 0 is false, all other numbers are true: bool(0) vs bool(-23)
    • ”” is false, all other string is true: bool("") vs bool('false')

Exercises:

  • 4a thru 4f in PythonExercises1.ipynb

♦ Recap & What’s next?

This session introduces you to the basic “rules of Python”, namely how Python code is written and understood by the Python machine to process commands. We also covered fundamental building blocks of code: variables and the most basic of operations you can do with them. Certainly, much more is to come, but soon you’ll find how you can do a tremendous amount with just this and a bit more basic understanding of the language.

Next up, we’ll look at basic data structures baked into the Python coding environment. These data structures enable us to create collections of objects and manipulate these collections in various ways…