A Brief Introduction to Python

(Press ? for help, n and p for next and previous slide; usage hints)

David Wright
February 27 2021

What We’ll Be Covering Today

  1. What is Python?
  2. Python programming basics
  3. Python demos

What is Python?

History of Python

  • Released in 1991 by Guido van Rossum
  • Has gone through three major versions: 1.x, 2.x, and now in 3.x
  • You will most likely only see 2.x and 3.x
    • 2.x end-of-life was 2020, but it may still be kicking around in some applications

The Python Language

  • High-level, abstract, and flexible language
    • Dynamically typed, manages memory itself, etc.
  • Easy to write, almost reads as regular English
  • Interpreted, not compiled
  • Many third party libraries with pre-written routines
    • Fast routines written in C (NumPy, SciPy)

The Python Interactive Shell

  • Interactive REPL on the command line
    • Read, Eval, Print, Loop (REPL)
    • IPython is a command shell specifically tailored to interactive Python
      • Has extra commands and functionality to improve the interactive experience

Sorry, your browser does not support SVG.

Python Programming Basics

What is a Program?

  • A sequence of instructions that specifies how to perform a computation
    • Input: Get data from the keyboard, a file, the network, or some other device.
    • Output: Display data on the screen, save it in a file, send it over the network, etc.
    • Math: Perform basic mathematical operations like addition and multiplication.
    • Conditional execution: Check for certain conditions and run the appropriate code.
    • Repetition: Perform some action repeatedly, usually with some variation.

What is a Programming Language?

  • Programming languages are formal languages designed to express computations
  • They have strict syntax
    • Mathematics example: \(3 + 3 = 6\) vs \(3 += 3\ 6\)
  • Programming languages are literal, unambiguous, and concise

Values and Types

  • Value: a basic thing a program works with (letters, numbers, etc.)
  • Type: a category of values (integers, strings, floats, etc.)
  • Python is dynamically typed. It determines the type of a variable based on its value
    • You don’t have to explicitly declare variable types

Sorry, your browser does not support SVG.

Variables and Expressions

  • Variables store values
  • Use underscores for multi-word variable names
    • Can’t start a variable with a number, include an illegal character (Ex: “@”), or name it after a Python keyword (Ex: “return”)
  • Expressions follow an order of operations (the usual PEMDAS for math operations)

Sorry, your browser does not support SVG.

  • Python Math operators
    • *, / Multiply and Divide
    • +, - Add and Subtract
    • ** Exponentiate
    • %, // Modulus and Floor Division

Built-in Data Structures

  • List
    • Collection of any types of objects, uses []
    • Mutable
  • Dictionary
    • Key-value pairs, uses {}
    • Access values with keys, keys are immutable
  • Tuple
    • Immutable version of lists, use ()
  • Set
    • Unordered collection of unique objects, uses {}
    • Mutable, but can be made immutable with frozenset()
    • Supports common operations on sets, such as intersection and union

Built-in Data Structures - List

Lists are 0-indexed. We can access the elements of a list with square braces and the index. Sorry, your browser does not support SVG.

Built-in Data Structures - Dictionary

We can access the paired values by dictionary[key] Sorry, your browser does not support SVG.

Built-in Data Structures - Tuple

Tuples are 0-indexed. We can access (but not modify!) the elements of a tuple with square braces and the index. Sorry, your browser does not support SVG.

Built-in Data Structures - Set

The least used (and often overlooked!) built-in. Useful operations include the union (|) and intersection (&). Sorry, your browser does not support SVG.

Functions

Create a Python function with the following boilerplate

def function_name(positional_args, keyword_args=default_val):
    """This is a docstring.

    ALWAYS write docstrings for your functions.

    """

    my_val = <some computations using the inputs>

    return my_val

See https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard

Functions (example)

Sorry, your browser does not support SVG.

  • The docstring was omitted for brevity in the example, always document your functions

Python and Whitespace

  • As you may have noticed in the slide on Functions, Python uses whitespace to delimit blocks
    • You may be familiar with languages that use curly braces or begin/end keywords
  • The official style guide mandates 4 spaces per indentation level, not tabs
    • Some text editors will handle the tab \(\to\) spaces conversion for you

Control Structures (if, for, while, etc.)

  • Three types of control structures
    • Sequential
      • The normal flow of code
    • Selection/Decision
      • if, elif, else
    • Repetition
      • while, for

Control Structures - Sequential

x = 5
y = 15
print("The difference is", y - x)
The difference is 10

Control Structures - Selection/Decision

Control the flow of code based on Boolean (True/False) values/expressions.

x = 5
y = 15

if x == y:
    print("The numbers are the same!")
else:
    print("The numbers are not the same!")
The numbers are not the same!

Control Structures - Repetition

Repeat based on conditionals or iterables

x = 12
y = 15
diff = y - x
my_list = [5, 10, 15]

while x < y:
    print("Difference is", diff)
    x += 1

for z in range(2):
    print("The value of z is", z)

for t in my_list:
    print("The value of t is", t)
Difference is 3
Difference is 2
Difference is 1
The value of z is 0
The value of z is 1
The value of t is 5
The value of t is 10
The value of t is 15

Script vs Interactive

So far, we’ve been working in the Python Interactive Shell. We can also bundle up our commands and run them from a .py script. The shebang #!/usr/bin/env python lets our computer know how to run the script if we don’t invoke it with python my_script. Sorry, your browser does not support SVG.

Python Demos

Visit the link below to get an online instance of a Jupyter Notebook with some demos.

The End

Acknowledgements

  • Snippets of Dr. Joseph Harrington’s Python demos were used with his permission
  • ThinkPython was used as a reference

Further Reading