Python 2 vs Python 3?
Time for Python 2 is running out... https://pythonclock.org/
Programming Languages: Compiled vs. Interpreted
What Matters: Execution Time or Development Time?
Why Python?
Free!!!
No license required
Interpreted language
Intuitive syntax
Object-oriented
Simple, but extremely powerful
Shallow learning curve and many resources
Dynamic typing
Integration with C/Java (great glue language)
Lots of API's with other software packages
Lots of built-in libraries and third-party extensions
Python is an Interpreted Language. What does that mean?
It's a little slower at time of execution (but there are ways to improve this)
There is the ability to interact in a call-and-response manner (like Matlab)
When considering the (computational) cost, what do we care about? Much more than (solely) the execution time, we care primarily about the amount of time between when you are told to solve a problem and when the computer spits out the solution:
Understand the problem.
Formulate/Identify an algorithm or solution technique.
Implement the technique in a program.
Test and debug the algorithm/program.
Execute the program.
Python is really great for rapid prototyping and quickly getting something up and running.
A Brief Overview of Methods for Interacting with the Python Interpreter
There are several "modes" for working with the Python interpeter:
Interactive Mode in the Shell (i.e. Terminal): In interactive mode, you enter python statements one at a time directly into the terminal window. Each statement is interpreted, executed, and returns results to the terminal window (unless you re-direct output, which you will learn later in the course). This mode allows for trial-and-error in writing correct python syntax, is useful for exploring language features, and supports prototyping. This mode is usually only used for very quick tasks that can be accomplished in a few lines of code.
Jupyter Notebook: Jupyter notebooks provide a comprehensive environment for interactive and exploratory computing. This mode provides a good format for documenting your methods (i.e. reproducible research) and for sequentially developing more complex programs. Jupyter notebooks provide some useful features that make developing programs easier such as numbered input/output prompts with command history (persistent across sessions and tied to each profile); full searching in this history and caching of all input and output; dynamic introspection of variables, functions, objects; auto completion of the namespace; and session logging. You will learn to leverage these features as we move through the course.
Batch Mode (i.e., as a Script): In batch mode, you enter all of your Python statements into a (saved) text file. You then tell Python to interpret and execute all of the statements in the file in a single "batch". The entire file must have correct syntax; a single error will abort the program. This method is useful for repeatedly running a tried-and-true set of instructions. Most programs in Python are used in this mode after (perhaps) being developed. We will learn how to do this later in the course.
Interacting with basic Python from the Terminal
The first mode of interacting with Python we will explore is interactive mode in the shell.
(1) Open the terminal/shell (if you forgot how, see the section on Unix commands above).
(2) At the command line, type: python
You should now see something similar to the following report in your terminal (PC and Mac reports vary slightly):
If Python has loaded correctly, the terminal command line will have changed from a $
symbol to >>>
. The >>>
is the Python prompt.
(3) Use the Python prompt as a calculator. Add a few numbers together (and hit enter). Do some more advanced math.
(4) To close out of Python (but remain in the terminal/shell), hit control-d on your keyboard or type exit()
. The $
prompt should return. Note that when you exit, all Python variables/values are erased from memory.
The terminal is the most primitive environment, but also universally available.
Lesson 1.2: Overview
During this lesson, you will learn the following:
A brief overview of Python as an interpreted language.
A brief overview of three methods for interacting with the Python interpreter:
"the shell"
Jupyter Notebooks
"batch mode"
How to interact with the Python interpreter through the terminal command line interface (also known as the "the shell")
How to open and interact with the Python interpreter through a Jupyter Notebook
A brief overview of how Python interprets different data types (values) and variable assignment in Python.
Interacting with enhanced IPython (interactive python) from the Terminal
The first mode of interacting with Python we will explore is interactive mode in the shell.
(1) Open the terminal/shell (if you forgot how, see the section on Unix commands above).
(2) At the command line, type: ipython
You should now see something similar to the following report in your terminal (PC and Mac reports vary slightly):
If Python has loaded correctly, the terminal command line will have changed from a $
symbol to In [1]:
. The In [1]:
is the Python prompt.
(3) Use the Python prompt as a calculator. Add a few numbers together (and hit enter). Do some more advanced math.
(4) To close out of Python (but remain in the terminal/shell), type exit
on your keyboard. The $
prompt should return. Note that when you exit, all Python variables/values are erased from memory.
The IPython terminal has a number of additional features that make it more friendly (and more powerful), including a number of so-called "magic" commands (documentation here)
Interacting with Python Using Jupyter Notebooks
Jupyter notebooks provide a comprehensive environment for interactive and exploratory computing. They also allow you to save your work for your own viewing or viewing by others.
You launch a Jupyter Notebook from the Anaconda Navigator (the main app) or "manually" from a terminal window as follows:
First, make sure you are in your "target" working directory by using the appropriate Unix commands to set your working directory to the Lab_Practicum folder on your desktop.
Launch Jupyter Notebooks by entering the following command into the command prompt:
This should open up a window that looks like the one below in your default web browser (I recommend you set your default web browser to something other the Internet Explorer if you are using a PC):
Note that your "notebook list is empty." The environment you are looking at is the Jupyter Notebook Dashboard which is the front-facing entity for the Jupyter Notebook App. The Jupyter Notebook App is a server-client application that allows editing and running notebook documents via a web browser. This environment will also provide a Python "kernel" for interpreting commands you give it from a notebook. The dashboard environment functions very much like the traditional file system you are used to interacting with on a Mac or PC operating system. Let's start creating some content; let's build your first notebook.
Click on "New" in the top-right hand of the Jupyter Notebook App and select "Python 3" (see image below):
This will launch a new browser window containing a new (blank) Jupyter Notebook.
To save this notebook under a new name, go to the very top of the file and click on the the word "Untitled" which will be right next to the jupyter "headline" at the top. Change the name of the file to something meaningful (like "YourlastnamePythonIntro").
Click on the browser tab that contains the Jupyter Notebook App (the file system view). You should now see your new file represented there as "YourlastnamePythonIntro.ipynb". This is an Jupyter Notebook file.
Return back to your notebook browser tab. You should be looking at something that looks like this:
This is a blank notebook. You have been provided a cell to start working in. You can designate cells to perform a couple of different functions. The cell you are looking at is currently designated as a code block, indicated by the "In" marker on the left side. The "In" indicator functions much the same as the command prompt.
A Jupyter notebook is divided into individual "cells". You can execute a given cell, either by clicking the "Run" button on the top menu, or by hitting "shift-enter" on your keyboard tells the Python kernel (interpreter) to execute the code block. Executing on a blank block generates a new block (a nice shortcut for creating new blocks to work in). Hit "shift-enter" a few times to create some empty cells. You can also use the "Insert" item on the banner to add more code blocks.
There are different types of cells. The two main ones (that we will use) are
Code
cells, live code connected to a Python interpreterMarkdown
cells, used for text. These support markdown, html, and LaTeX!
Activity: Open a Jupyter Notebook and play around with creating new text cells and coding cells.
Select a cell by clicking to the left of the cell
To insert a cell above, select the side of a cell then press a
To insert a cell below, select the side of the a cell and press b
Executing Code in the Jupyter Notebook
Anything typed in a Jupyter notebook Code
cell is "live code". When you click "Run" (or type Shirt-Return), the contents of that cell are sent to the Python interpreter and executed, as though you had typed it in an interactive IPython terminal session.
The simplest type of code to execute simply evaluates an expression, which is kind of like asking Python, "tell me the value of this expression"...
The numbers in provide the "numbered input/output prompts with command history" provides a record of what commands the Python interpreter has executed (and the order that it executed them in).
Activity: enter a cell below this one and play around entering an evaluating differnt types of input.
Strings
basic math
Data Types in Python
Literal values in Python have a type associated with them. We can use the built-in type()
function to determine the type of data.
Python has a special value None
(like Null in other languages)
Operators and Expressions
An operator is a special symbol that represents a simple computation
arithmetic operators
string operators
boolean operators
An expression is a programming construct that yields a value when evaluated. Anything that results in a value is a valid expression:
arithmetic expressions yield a numeric value
string expressions yield a string value
boolean expressions yield a boolean value
The same operator will behave differently on a different type of data.
Arithmetic Operators
The first type of operators we will learn are the arithmetic operators:
Addition, Subtraction: + -
Multiplication, (Float) Division, Integer (Floor) Division: * / //
Exponentiation: **
Modulus (remainder): %
Python supports C-style shifting and masking
1<<16
,x&0xff
,x|1
,~x
,x^y
Integer Arithmetic
Integers provide exact representations for whole numbers
Arithmetic operations between integers produce integer results (evaluate these in Python):
In Integer Division (the // operator), if the result is not naturally an integer, it is made so by truncating the answer - fractional parts are discarded:
Arithmetic Involving Different Types
When both operands are integers, Python uses integer arithmetic (for everything but division, which needs to be explicit).
If either of the operands is a floating-point number, Python uses floating-point arithmetic.
Essentially Python coverts one of the two values (so that both values have the same type); this is called type coercion.
Python has built-in functions for explicit type conversion:
int()
: forces integerfloat()
: forces floatstr()
: forces string
These functions do not always work for everything (functions/operators often depend on type)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-51-b9fcb4cd3570> in <module>
----> 1 int('5.5')
ValueError: invalid literal for int() with base 10: '5.5'
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-54-7124e8e12e61> in <module>
----> 1 float("hello")
ValueError: could not convert string to float: 'hello'
Order of Operations
For expressions involving multiple operators, Python follows an explicit ordering for evaluating each part:
()
: Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want, starting from the inner most parentheses and working outward.Unary operators (e.g., designating a negative number) have the next highest precedence.
**
: Exponentiation has the next highest precedence.*
,/
,//
: Multiplication and Division have the same precedence.+
and-
: Addition and Subtraction have the same precedence.Operators with the same precedence are evaluated from left to right (except exponentiation).
Examples (evaluate these expressions by hand and check your work in Python):
"Shortcut" Operators
Some operations (such as updating a variable) are used so frequently that there exist special operators defined to reduce the need for typing:
The expression:
a = a + 5
can be abbreviated as:
Similarly:
Note that
(a += 5)
evaluates differently from(a = +5)
Variables
In Python, each data item has two aspects:
its type (how many bits are used and how to interpret them?)
its value (the interpretation or “meaning” of those bits)
A variable is a name that refers to a value.
Some programming languages (e.g., Java, C, C++) are “statically typed” (meaning that you have to announce the type of variable before using it)
declaration: an announcement of a given variable name
instantiation: the allocation of memory to hold that data type
assignment: assigning a data value to the variable
In Python, all three steps happen together with assignment (no need to declare, just assign)
Python is “dynamically typed” (convenient, but with caveats)
"Everything" in Python is a variable (even functions, classes, modules)
Identifiers
An identifier is a sequence of characters we use to name a variable and other program elements (such as functions and modules)
A valid Python identifier must:
consist of letters, numbers, and the underscore characters only and
begin with a letter or an underscore
Examples:
Reserved Words
An identifier that is used for a specific purpose by Python is called a reserved word or keyword.
Python reserved words are:
Relational and Logical Operators
Review: in previous lessons we learned about algebraic operators (+, -, /, *, etc.) that take (typically) two operands and return a numerical value.
Today's lesson will focus on using relational and logical operators to develop boolean expressions.
A boolean expression is an expression that is either true or false.
Recall that the boolean data type ('bool') can take on two values: TRUE or FALSE
Boolean expressions return boolean values.
Boolean expressions use either relational or logical operators:
Relational Operators: operators with two numerical operands that yield a True/False result:
>, <, <=, >=, ==, !=
Logical Operators: operators that combine boolean expressions:
and
,or
,not
Control Structures
Conditional Execution
Perform operations conditionally
if
elif
else
NOTE: Spacing Matters! Block structure dictated by indentation (white space)*
Activity: write a simple if
statement that:
checks to see if a variable is an integer
Activity: write a nested if
statement that:
determines if a variable is a string, int, or float
Activity: write a nested if
statement that:
determines if a variable is a string, int, or float
if the variable is an int, convert to a float and take modulo 3.
if the variable is a float, convert it into a string
if the variable is a string but does NOT start with the letter s, return the string. Otherwise, print null.
Activity: write an if
statement that does the following:
Reads in a fuel economy of a vehicle
checks the value to make sure it is type float and prints and error otherwise
tells the user if the fuel economy is good, fair, or poor (you pick the values).
Do not write two seperate if
statements, write nested if
statements.
The while
loop
A
while
loop contains a statement or block of statements that are repeated indefinitely as long as some boolean expression is true. The (Boolean) test is performed at the beginning of the loop.Generic Format:
There must some statement(s) inside the while loop that update the boolean expression (ultimately making it false), otherwise your program will get stuck “in an infinite loop”!
The break
statement
A
break
statement causes you to jump out of the loop (i.e., if this happens, exit loop)
The continue
statement
A continue statement causes you to skip the rest of the current iteration of a loop, but continue the loop.
The for
loop
A
for
loop provides the means to iterate over a sequence of valuesGeneric Format:
break
andcontinue
also work hereExamples to follow shortly...