Intro to Python Programming Language¶
(With a short intro to Jupyter along the way)¶
Some content copied from the official python tutorial. See the tutorial for much more in-depth coverage.
Follows reading in 'Real World Instrumentation', Chapter 3 (pgs. 61 to 121).
Other Resources: https://www.youtube.com/watch?v=rkx5_MRAV3A
Instructions: First spend some time navigating the Jupyter workspace. Also try out the IPy workspace and the Spyder workspace. These are all called Integrated Development Environments (IDEs). They give you a command line to execute your scripts. They often have a text editor for writing code. They can help you display your variables to look at what is in the workspace.
Importing modules and packages¶
Python does not explicitly load the libraries of functions (called modules). This saves on memory and data efficiency, but it means we must load the ones that we need. There are several different approaches to loading modules. Here, we will use the object oriented approach and load each module into a variable name that we can call or operate on. The most common modules that we need are numpy, matplotlib, and os
# Import Numpy
import numpy as np
# Import plotting library
import matplotlib.pyplot as plt
# import....
from os import *
Data types in Python¶
Note: As you make code, you must pay particular attention to data types. Each data type has restrictions on what kind of operations can be peformed, e.g. you can't do arithmetic on a text string. Many of the errors and problems that you will encounter arise when you try to use a function or operation that was not meant for a data type. File this away for future reference.
# Comments are anything that comes after the "#" symbol
a = 1.57 # assign 1.57 to variable a
b = 'hello' # assign "hello" to variable b
type(a)
# query the data type
b?
# can recast some data types as others:
# Note that i
print(int(a))
Arithmetic operators:¶
+, -,*, /, **
a = 2
b = 4
# Divide
a/b
c = a/b; print(c)
Multiply a and b:
#Answer:
print(a*b)
print(b*a)
Compute a to the power of b:
#Answer:
a**b
# but not all types can be converted:
bnbr2 ='hello'
int(bnbr2)
Getting help()¶
plt?
help(plt.plot)
Lists, tuples, and dicts¶
# This is a list. It has multiple elements and can be of mixed data types.
barnyard = [3,'chicken','4','pig',2.2,'goat']
# The list can be sub-indexed to access one element at a time:
print(barnyard[1])
# The list is mutable, meaning it can be changed
barnyard.append('horse')
print(barnyard)
# This is a tuple. It has multiple elements and can be of mixed data types, but it is immutable.
junkyard = ('Ford','Chevy','John Deere')
# The tuple can be sub-indexed :
print(junkyard[2])
# The tuple is immutable, it can not be increased or decreased. This is another example of an operation that is
# prohibited by data type.
junkyard.append('Tesla')
print(junkyard)
Conditionals: if, elif, else¶
x = 100
if x > 0:
print('Positive Number')
elif x < 0:
print('Negative Number')
else:
print ('Zero!')
----- Complete the exercises below, adding your answers as notes. ----¶
What data types are barnyard1, barnyard2, barnyard3, and barnum?¶
barnyard1 = ['3','chicken','4','pig','2','goat']
barnyard2 = 55
barnyard3 = 'horses'
barnum = 4.5
# Answer: What data types?
Indexing:¶
Arrays,lists, and touples can all be indexed. Python uses ':' (colons) to separate the index bounds,e.g. start:stop or from:to. All indices are encapsulated within a hard bracket [].
Example 1: barnyard1[3:5] #This tells python to subindex elements from barnyard1 starting at 3 and ending at, but not including, 5. In practice, elements 3 and 4 will be indexed.
Example 2: barnyard1[0] #This tells python to subindex the first element.
So far we have indexed with a step = 1. It is also possible to index using steps of e.g. 1, 2, 3. This looks like: barnyard1[start:stop:step]
Example 3: barnyard1[1:7:3] #This tells python to subindex from the 2nd element through the 6th element by steps of 3.
Indexing: What does this code do? Answer, then uncomment and execute to check your answer.¶
# Which element is returned?
barnyard2 = [3.14,'chicken',4.5,'pig',2,'goat',33,'cows',12,'guinea foul']
barnyard2[-1]
# What does this code do? Answer and then uncomment to test.
#newobj = barnyard2[::3]
#print(newobj)
#newobj = barnyard2[2::2]
#print(newobj)
# What does this code do? Answer and then uncomment to test.
#print(barnyard2[::-2])
# Note that Python does not make a separate copy unless it is forced to do so.
b = barnyard2
# b is a pointer to the original list barnyard2
b[4] = 'gorillaz'
# Barnyard got modified as well. Woops.
print(barnyard2)
print(b)
# Make an explicit copy
b = barnyard2.copy()
b[4] = 'goat'
print(b); print(barnyard2)
# Subindex the text element in list position 1 - what is the result?
barnyard2[1][3]
#Make a new list that is 6 elements long, insert the value 6 into each element.
alist = [6,6,6,6,6,6]
# Append the term 'text' and the number 83.08 to your list.
alist.append('text')
alist.append(83.08)
#Why does this fail?
alist[8] = 'more text'
#print(alist)
------ Some conceptual programming distinctions -------¶
Functional programming.¶
Functional programming decomposes a programming task into a set of inputs and outputs. In strictly functional programming, only the outputs are modified.
Procedural vs. declarative programming.¶
Procedural programming tells the computer how to complete a set of tasks.
Example of procedural:
>> First do...
>> Next do ...
>> Last print...
Example of declarative:
>> Give me all the values between 'beginning' and 'end'. # The language decides what is more efficient.
Additional data types in Python¶
Break into your teams. Ask each group to investigate one aspect of the programming environment and then report back with a simple lesson for the class. Team lists are on Brightspace.¶
Additional Notes¶
NOTE: You can use the tab to autocomplete. NOTE: You can use the up/down arrow keys to cycle through the command history.
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Additionally, the following a built in functions which are always available in your namespace once you open a python interpreter
abs() dict() help() min() setattr() all() dir() hex() next() slice() any()
divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray()
filter() issubclass() pow() super() bytes() float() iter() print() tuple()
callable() format() len() property() type() chr() frozenset() list() range()
vars() classmethod() getattr() locals() repr() zip() compile() globals() map()
reversed() __import__() complex() hasattr() max() round() delattr() hash()
memoryview() set()