Getting Started in Python

Why Python?

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:

In [9]:
print("Hello World!") 
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

In [10]:
print("Saw 'em off")
Saw 'em off

to

In [11]:
print("Søren Kierkegaard and Jean-Fraçois Lyotard")
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

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
  • inform the reader, often yourself, of what a particular piece of code is trying to do
  • indicate the designed output, result, etc. of piece of code
  • make the code more readable

Any code you submit in this class must be well commented!

You use the pound (aka hashtag) to comment out the rest of a line

In [13]:
#This next line should compute 9*9 + 19 = 100
print(9*9 + 19)

#You can also make comments inside a line
9*9 #+ 19
100

Out[13]:
81

There are also ways to make multiline comments by use a triple quote '''

In [4]:
'''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.")
I am the very model of a modern major general.

Errors

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.

In [8]:
#This is a good bug because the python interpreter complains
9*9 +
  File "<ipython-input-8-64b47963658c>", line 2
    9*9 +
         ^
SyntaxError: invalid syntax
In [14]:
#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.
Out[14]:
28

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.

Indentation

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.

In [15]:
#If I improperly indent, my code won't work
print("Not indented")
    print("indented, but it shouldn't be")
  File "<ipython-input-15-0b1b509e390c>", line 3
    print("indented, but it shouldn't be")
    ^
IndentationError: unexpected indent

Notice that none of my code executed because of the indentation error.

Variables

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

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.

In [23]:
#assign the value 2 to x
x = 2
print(x*2)

#check that x is an integer
type(x)
4

Out[23]:
int

Floating Point

Floating point types are numbers that do have a fractional part. Most numbers in engineering calculations are floating point types.

In [24]:
#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)
x = 2
<class 'float'>
(2 / 4.2)**3 = 0.10797969981643449

Built-in Mathematical Functions

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.

In [28]:
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)
cos( 3.14159 ) = -0.9999999999964793
The base of the natural logarithm is 2.718281828459045
The value of pi is 3.141592653589793

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

In [29]:
# 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)
7 divided by 3 is 2 remainder 1
851 divided by 13 is 65 remainder 6

Input

You can prompt the user for input using the input command:

In []:
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.

The Great Beyond

We've only scratched the surface of what python can do. For example, we can generate graphs with relative ease:

In [4]:
%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.

Strings and Overloading

A string is a collection of characters, and needs to be inside quotes:

In [5]:
#This is a string
aString = "Coffee is for closers."
print(aString)
print("aString")
Coffee is for closers.
aString

You can also subset a string using brackets. Note, 0 is the first character in a string.

In [7]:
aString[0]
Out[7]:
'C'

You can also get a range of characters in a string using the colon:

In [12]:
aString[1:6]
Out[12]:
'offee'

Negative subsets start at the end of the string (i.e., -1 is the last character of the string).

In [8]:
aString[-1]
Out[8]:
'.'
In [9]:
aString[-5:-3]
Out[9]:
'se'

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,

In [10]:
'Negative Ghostrider: ' + 'the pattern is full'
Out[10]:
'Negative Ghostrider: the pattern is full'
In [11]:
'a' + 'b' + 'c'
Out[11]:
'abc'

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

In [58]:
'The roof, ' * 3
Out[58]:
'The roof, The roof, The roof, '

However, 'The roof, ' * 3.15 is not defined and will give an error:

In [59]:
'The roof, ' * 3.15
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-59-b68ac6dcc130> in <module>()
----> 1 'The roof, ' * 3.15

TypeError: can't multiply sequence by non-int of type 'float'

The upshot is that only an integer times a character/string makes sense. The order of operations is respected

In [12]:
'The roof, ' * 3 + 'is on fire...'
Out[12]:
'The roof, The roof, The roof, is on fire...'

Minus makes sense, but only sometimes, so it is not allowed.

In [62]:
'The roof, ' - 'oof'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-62-c999e0505465> in <module>()
----> 1 'The roof, ' - 'oof'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Branching (If statements)

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

In [15]:
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)
What is your opinion of student? Should get F
A

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:

In [19]:
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,".")
No, 3.142857142857143 is not a good approximation of 3.141592653589793 .

Branching statements are most powerful when combined with iteration.

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.

In [21]:
#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")
Our approximation of pi is 3.1415920000002227
It took us 3184 guesses to approximate pi

We can do the same thing and tighten the tolerance

In [29]:
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")
Our approximation of pi is 3.141592644990321
It took us 318529 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