In this course we are going to use python version 3. Python is a powerful and widely accepted programming language that can do just about anything lower-level programming languages like Fortran, C, and C++ can. By learning to program in python, you will learn the skills you need to program in any other computer language with relative ease.
Note: The Guttag book makes references to python 2.7. Do not be afraid, almost everything we will do works in python 2 and python 3. This is a good point to make a case for backwards compatibility.
In almost any computer language the first thing you do is create a program called "Hello world!", where you make the computer say, in text, "Hello World!" In python you simply start a python session and type:
print("Hello World!")
The part to type in the gray box and the output is directly below it. We could have it print any type string of characters, from
print("Saw 'em off")
to
print("Søren Kierkegaard and Jean-Fraçois Lyotard")
Note how python supports the unicode character set so that we can get those fancy letters.
I'm running my code in interactive mode, which means the result of each line is displayed when I enter the line. It is more common to put your code into a separate file and then execute it by typing
python codename.py
where "codename.py" is the name of your file.
You can start the python interpreter in interactive mode by typing "python" in the terminal if you are in a Mac or linux. You can also open up a graphical shell for python called IDLE in Windows, Mac, or linux.
When you install python on a machine, install the latest version of python 3.
Comments are your friend. They can be time consuming to add, but never have I looked back at old code and regreted adding them.
A comment is a annotation in your code to
You use the pound (aka hashtag) to comment out the rest of a line
#This next line should compute 9*9 + 19 = 100
print(9*9 + 19)
#You can also make comments inside a line
9*9 #+ 19
There are also ways to make multiline comments by use a triple quote '''
'''The beginning of a multiline comment.
This comment will be followed by meaningless
code. Enjoy '''
print("I am the very model of a modern major general.")
In any code you write, you'll screw something up. In the parlance of our times these errors are called bugs. Now there are good bugs and bad bugs. The good bugs get caught by python and it will complain when it finds them. The bad bugs are insidious little beings that made your code do the wrong thing, without you knowing it.
Even experiences programmers write code with bugs. There are a long serious of procedures to try to rid a code of bugs, but even the most sophisticated software quality assurance techniques will not catch every one.
Let's look at a good bug and a bad bug.
#This is a good bug because the python interpreter complains
9*9 +
#This is a bad error because it doesn't do what you might think
#Say you want to compute (3 + 5)^2 = 8^2 = 64, but you actually input
3 + 5**2
#You don't get the correct answer, and no one tells you that you're wrong.
This is an example of the power and feebleness of computers. A computer can do anything you tell it to, but it doesn't necessarily do what you want it to.
Python is, by design, very picky about how you lay out your code. It requires that code blocks be properly indented. We'll discuss what code blocks are later, but your code needs to be properly aligned to make this work.
#If I improperly indent, my code won't work
print("Not indented")
print("indented, but it shouldn't be")
Notice that none of my code executed because of the indentation error.
Almost every code needs to store information at some point in its execution. Information, or data, is stored in variables. There are different types of variables for different types of data and we will discuss many of them here.
For a complete list of the python data types, see https://docs.python.org/2/library/stdtypes.html
Integers are whole numbers, including the negatives. They never have a fractional, or decimal, part and should only be used for data that is a count.
To assign an integer to a variable use the equals sign.
#assign the value 2 to x
x = 2
print(x*2)
#check that x is an integer
type(x)
Floating point types are numbers that do have a fractional part. Most numbers in engineering calculations are floating point types.
#Now make some others floating point variables
y = 4.2
print("x =",x)
print(type(y))
#note that exponentiation is **
z = (x / y)**3
print("(2 / 4.2)**3 =",z)
There are almost every common mathematical function you might need for python already built in.
See https://docs.python.org/3.4/library/math.html for the complete list.
import math as math
#take cosine of a number close to pi
theta = 3.14159
trig_variable = math.cos(theta)
print("cos(",theta,") =",trig_variable)
#use the exponential to give me e
e = math.exp(1)
print("The base of the natural logarithm is",e)
#python has a built-in pi as well
print("The value of pi is",math.pi)
Notice how in the print statements, if I give it multiple arguments, it prints each with a space in between.
There are two non-obvious mathematical operators, integer division: //, and the modulus (or remainder): %
# 7 / 3 is 2 remainder 1
print("7 divided by 3 is",7//3,"remainder",7%3)
print("851 divided by 13 is",851//13,"remainder",851%13)
You can prompt the user for input using the input command:
user_value = input("Enter a number (just type 7): ")
user_value = float(user_value)
if user_value == 7:
print("Correct, we have a winner")
print("Claim your prize")
else:
print("You guessed poorly.")
Notice that in this example we used an if-else statement. The if-else statement is a way to execute different parts of the code based on some conditional expression. This type of execution is sometimes called branching or selection.
Also notice the indentation in the if-else block.
We've only scratched the surface of what python can do. For example, we can generate graphs with relative ease:
%matplotlib inline
#this is only for the notebook and is not needed in regular code.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp');
In future lectures we'll talk about how to use the advanced features that are available to us in python in more detail.
A string is a collection of characters, and needs to be inside quotes:
#This is a string
aString = "Coffee is for closers."
print(aString)
print("aString")
You can also subset a string using brackets. Note, 0 is the first character in a string.
aString[0]
You can also get a range of characters in a string using the colon:
aString[1:6]
Negative subsets start at the end of the string (i.e., -1 is the last character of the string).
aString[-1]
aString[-5:-3]
With characters (and strings) the + operator is overloaded. What we mean by overloaded, it is defined so that the idea of what addition means is conferred to strings. Therefore,
'Negative Ghostrider: ' + 'the pattern is full'
'a' + 'b' + 'c'
The + operator concatenates (or smushes together) the strings/characters it operates on.
The multiplication operator is similarly overloaded, though it is not as general. It is simple to think about 'The roof, ' * 3
'The roof, ' * 3
However, 'The roof, ' * 3.15 is not defined and will give an error:
'The roof, ' * 3.15
The upshot is that only an integer times a character/string makes sense. The order of operations is respected
'The roof, ' * 3 + 'is on fire...'
Minus makes sense, but only sometimes, so it is not allowed.
'The roof, ' - 'oof'
Sometimes you want to execute code differently based on the value of a certain variable. This is most commonly done in if - else constructs. Here's an example
instructors_opinion = input("What is your opinion of student? ") #'Not annoying'
grade = ''
if (instructors_opinion == 'annoying'):
grade = 'F+'
elif (instructors_opinion == 'Not annoying'):
grade = 'B+'
else:
grade = 'A'
print(grade)
This is a silly example, students cannot be annoying. It is a joy to teach each and every one of them. It is more likely to have a condition like this:
import math
pi_approx = 22/7
if math.fabs(pi_approx - math.pi) < 1.0e-6:
print("Yes, that is a good approximation")
else:
print("No,",pi_approx, "is not a good approximation of", math.pi,".")
Branching statements are most powerful when combined with iteration.
Iteration executes a piece of code repeatedly, based on some criteria. In this example we will try to find a good approximation to pi.
#this code finds a decent approximation to pi
converged = 0
guess = 3.14
iteration = 0
eps = 1.0e-6 #this is my tolerance for approximating pi
converged = abs(guess - math.pi) < eps #0 if false, 1 if true
while (converged == 0):
guess = guess + eps/2
converged = abs(guess - math.pi) < eps
iteration += 1 #same as iteration = iteration + 1
print("Our approximation of pi is", guess)
print("It took us", iteration,"guesses to approximate pi")
We can do the same thing and tighten the tolerance
guess = 3.14
iteration = 0
eps = 1.0e-8
converged = abs(guess - math.pi) >= eps
while (converged==1):
guess = guess + eps/2
converged = abs(guess - math.pi) >= eps
iteration += 1
print("Our approximation of pi is", guess)
print("It took us", iteration,"guesses to approximate pi")
The while loop is an important form of iteration. Another type is the for loop which executes a set number of times based on a set condtion. We will talk about that next time