Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News Sign UpSign In
| Download
Views: 1369
Image: ubuntu2004
Kernel: Python 3 (system-wide)

nuwc_nps_banner.png

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:

    1. Understand the problem.

    2. Formulate/Identify an algorithm or solution technique.

    3. Implement the technique in a program.

    4. Test and debug the algorithm/program.

    5. 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:

  1. 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.

  2. Launch Jupyter Notebooks by entering the following command into the command prompt:

jupyter notebook

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.

  1. 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.

  1. 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").

  2. 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.

  3. 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.

  1. 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.

  2. There are different types of cells. The two main ones (that we will use) are

  • Code cells, live code connected to a Python interpreter

  • Markdown cells, used for text. These support markdown, html, and LaTeX!

x="hello from the other side" print(x)
hello from the other side

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).

5+4
9
1 + 2
3
3 * 4 / 9
1.3333333333333333
'this is a string'
'this is a string'
# long integers (arbitrary precision) 2**3
8

Activity: enter a cell below this one and play around entering an evaluating differnt types of input.

  • Strings

  • basic math

3**3
27
"a"+"b"
'ab'

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.

type(5)
int
type(3.1)
float
type(1+1j)
complex
type(False)
bool
type('hello world')
str

Python has a special value None (like Null in other languages)

type(None)
NoneType

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):

3+2
5
3-2
1
3*2
6
3 % 2
1
  • 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:

3 // 4
0
4 // 4
1
5 // 4
1
5 % 4
1
5 / 4.0
1.25

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 integer

    • float(): forces float

    • str(): forces string

  • These functions do not always work for everything (functions/operators often depend on type)

int(5.6)
5
float(5)
5.0
str(5)
'5'
float('5.0')
5.0
int('2')
2
int('5.5')
--------------------------------------------------------------------------- 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'
int(float('5.5'))
5
float("hello")
--------------------------------------------------------------------------- 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:

  1. (): 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.

  2. Unary operators (e.g., designating a negative number) have the next highest precedence.

  3. **: Exponentiation has the next highest precedence.

  4. *, /, //: Multiplication and Division have the same precedence.

  5. + and -: Addition and Subtraction have the same precedence.

  6. 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:

a +=5
  • Similarly:

b -= 7.1 # same as: b = b – 7.1;
c *= 2 # same as: c = c * 2;
d /= 2.0 # same as: d = d/2.0;
e %= 3 # same as: e = e % 3;
  • 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

# Relational operator examples x = 5 # assignment operator
x # check the value of x, everything that follows is a relational operator
5
x > 5
False
x < 5
False
x <= 5
True
x >= 5
True
x == 5
True
x != 5
False
1 <= x <= 10 # python supports this compound structure
True
# Logical Operator Examples #If we define the following... a = True b = False c = True
a or b
True
a and b
False
a and (b or c)
True
a or (b and c)
True
not a or not b
True
not a and not b
False
a or b
a ^ b
1

Control Structures

Conditional Execution

  • Perform operations conditionally

    • if

    • elif

    • else

NOTE: Spacing Matters! Block structure dictated by indentation (white space)*

score = 67 print (score )
67
if (score > 70): # conditional statement print('Passed') # execution statement
if score > 70: # conditional statement print('Passed') # execution statement if true print("another message") else: print('Failed') # execution statement if false
Failed
if score >= 90: print('You got an A!') elif 80 <= score < 90: print('You got a B.') elif 70 <= score < 80: print('You got a C.') else: print('See the instructor.')

Activity: write a simple if statement that:

  • checks to see if a variable is an integer

a=1 type(a) if(type(a)==int): print("a is integer") else: print("not")
a is integer
type

Activity: write a nested if statement that:

  • determines if a variable is a string, int, or float

a=['list'] type(a) if(type(a)==str): print("this is a string") elif(type(a)==int): print("it's an int") elif(type(a)==float): print("float") else: print("dunno")
dunno

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.

a=['list'] type(a) if(type(a)==str): print("this is a string") elif(type(a)==int): print("it's an int") print(float(a) % 3) elif(type(a)==float): print("float") else: print("dunno")

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.

tmpstr = input("enter a value for fuel economy") int(tmpstr) if(tmpstr == 25): print("why")
enter a value for fuel economy

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:

while boolean_expression: statement1 statement2 statement3 update_statement # prevent an infinite loop
  • 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.

i = 1 while i <= 5: print(i) i += 1 # the critical update statement print("Done.")
1 2 3 4 5 Done.
i = 0 while i < 5: print(i) if i == 3: break i = i + 1 print("Done.")
0 1 2 3 Done.
i = 0 while i < 5: i = i + 1 if i == 3: continue print(i) print("Done.")
1 2 4 5 Done.

The for loop

  • A for loop provides the means to iterate over a sequence of values

  • Generic Format:

for var in sequence: statements
  • break and continue also work here

  • Examples to follow shortly...

for i in range(10): print(i) a=1 b=2 c=3 import numpy as np x=1 + 2j np.angle(x)
0 1 2 3 4 5 6 7 8 9
1.1071487177940904

Next Lesson: 1.3 Strings...