PC204 Lecture 1

Tom Ferrin

tef@cgl.ucsf.edu

Course Logistics

Logistics (cont.)

  • Course prerequisites:
    • You have a good understanding of computers, files, and directories
    • You know how to send and receive e-mail with attachments
    • You want to learn how to write useful, good quality programs
  • Computing resources:
    • The best approach is to set up your laptop with Python and any other programming tools you might need. If you have a Mac or Windows just download and install Python from www.python.org
  • Grading:
    • Homework: 50%
    • Final project: 50%
    • Homework due no later than beginning of class the following week
    • Email homework to pc204@cgl.ucsf.edu

Logistics (cont.)

  • Think Python vs Course Lectures:
    • We’ll basically be marching through Think Python from beginning to end. The lecture notes cover most of the same material but often in a different fashion, so you’ve got the opportunity to think and learn about concepts in a couple different ways.
    • Course slides can be viewed at www.cgl.ucsf.edu/Outreach/pc204/lecture_notes/weekN/LectureN.html
  • Python 2 vs Python 3
    • Python 3.x is the present and future of the language.
    • Python 2.7 is the widely used predecessor. They are 98% compatible!
    • We'll use Python 3 for most code examples, but will point out any differences between Python 2 and Python 3 along the way.
    • For more information see wiki.python.org/moin/Python2orPython3
[How To Write Good Code]

How Hard Can Good Code Be?

Some famous computer software bugs

  • Guidance computers crash on Ariane 5 rocket due to floating point overflow - rocket self destructs - $370M (Jun 4, 1996)
  • USS Yorktown Navy destroyer - seaman enters 0 in wrong input field causing network of 27 PCs running Windows to crash and leaving ship dead in the water (Sep 21, 1997)
  • Near nuclear war - early warning system mistakes moon for massive incoming barrage of warheads - launch of counterstrike halted by sharp-eyed technician (Oct 5, 1960)
  • Pentium FDIV microcode bug yielding incorrect results - cost Intel $475M to replace CPUs (Oct 1994)
  • Automated baggage system at Denver airport would randomly route bags to wrong planes - $1.1M/month for over 9 months!
  • Therac-25 radiotherapy machine - race condition in software caused patients to receive massive overdoses of radiation resulting in several deaths during 1985-87

Why Python?

  • Python has many language features that facilitate writing Good Code. It's a widely-available, easy-to-learn, object-oriented, interpreted language that provides high-level language constructs. Python home page: www.python.org
  • Alternatives programming languages:
    • C and C++ - Standardized, efficient general purpose languages with lots of features but pretty steep learning curve
    • Fortran - Same disadvantages as C; mostly used for numerically intensive programming tasks
    • Java - Widely available, but more "systems oriented" and often requires more coding than Python to accomplish the same task; popular for client-side web applications
    • Javascript - Mostly used for adding dynamics to web pages; no object-oriented language features
    • Perl - Similar to Python (high-level, general-purpose, interpreted), but its syntax is often strange and it's not easy to build large and complex programs

The Python Interpreter

$ python3
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print("Hello world!")
Hello world!
>>> course = "pc204"
>>> print(course)
pc204
>>> pi = 3.14159265
>>> print(pi)
3.14159265
>>> exit()
$

What is a Program?


 
A program is just a sequence of instructions that specify how to perform a computation. Programs typically take some kind of input (e.g., a file of data values), do something with it (e.g., mathematical operations), and then display it on the computer screen or output data to a file. Sometimes you check for certain conditions (e.g., unexpected data values) and do something different if that condition is true, like print out an error message. And sometimes you repeat operations over and over again.

Make our Python commands into a program

  • Step 1 - Create a file named "prog.py" containing the same commands:
    #
    # hello.py - a simple python program
    # Author: Tom Ferrin
    # Updated: Sep 25, 2018
    #
    print("Hello world!")
    course = "pc204"
    print(course)
    pi = 3.14159265
    print(pi)
    
  • Step 2 - Execute the commands in the file:
    $ python3 prog.py
    Hello world!
    pc204
    3.14159265
    $
    

Our first program (cont.)

  • Text preceeded by #'s are called comments and are ignored by the Python interpreter. But comments are a vital component of all programs! They provide a means of informing a reader about your code. Stuff like who wrote it and when, or what version it is, or why some particular operation is being done. Comments are a mandatory component of all Good Programs.

  • For all homework assignments and final project:
    • Write your code as one of more .py files
    • Always include code that demonstrates that your program is working properly
    • Make sure your name is included in each file as a comment
    • If your program is written to run under Python 2 make sure you note this at the beginning of the file
    • Email you program as an attachment to pc204@cgl.ucsf.edu
      (Please don't mail to individual course instructors or the TA.)

The Program Development Cycle

In a typical traditional programming language...

  1. Edit
    • Input = mental vision of solution to a problem
    • Output = source code
  2. Compile
    • Input = source code
    • Output = errors, warnings, object code
  3. Link
    • Input = object code
    • Output = errors, warnings, exectuable code
  4. Execute
    • Input = executable code and input data
    • Output = errors (if bugs still presesent) and results
  5. Test and Debug
    • Input = exectuable code and "known" input data
    • Output = results to be checked against correct answers

 
Repeat steps above until your program works like it should

The same using an "interpreted" programming language

  1. Edit
    • Input = mental vision of solution to a problem
    • Output = source code
  2. Compile
    • Input = source code
    • Output = errors, warnings, object code
  3. Link
    • Input = object code
    • Output = errors, warnings, exectuable code
  4. Execute Interpret
    • Input = executable source code and input data
    • Output = results
  5. Test and Debug
    • Input = exectuable source code and "known" input data
    • Output = results to be checked against correct answers

And the same using Python in particular

  1. Edit
    • Input = mental vision of solution to a problem
    • Output = source code
  2. Python Interpreter
    • Input = source code and input data
    • Output = errors (if bugs present) and/or results
  3. Test and Debug
    • Input = source code and "known" input data
    • Output = results to be checked against correct answers

 
Repeat steps above until your program works like it should

Programing Errors

There are several kinds of errors you will encounter when programming:
  • Syntax errors occur when something is wrong with the structure of your program.
  • Runtime errors occur when when the Python interpreter tries to perform the instructions you told it to do but something isn't right with those instructions.
  • Semantic errors occur because you instructed the Python interpreter to do something other than what you intended. With semantic errors, your program appears to run correctly but doesn’t yield the correct results.

 
Debugging is the process you go through tracking down and fixing each of these types of errors. Note that in order to fix semantic errors, you need to know what results your program should be producing. This typically means you need some test data that you can feed your program.

Variables, Expressions, and Statements

Values

  • All programming languages support the fundamental programming concepts of variables and values. Values are things like numbers or strings of characters. Variables are just names that refer to values.
  • These things are values:
    • 1
    • 3.14159265
    • "Hello there, my name is Tom."
  • The three values above are actually of three different types: an integer, a floating-point number (most often just called a float), and a string. Python has many more types of values, but these three are the most common.

Variables

  • You associate a value with a variable by using an assignment statement. Assignment statements are just a variable name, an equal sign, and a value:
    • one = 1
    • pi = 3.14159265
    • my_string = "Hello there, my name is Tom."
  • Variable names can be anything you choose, so long as they begin with a letter or underscore ( _ ) and only have letters, numbers, or underscores in them. [Exception: variable names cannot be Python keywords - see below.] These are all valid variable names:
    • foundit, default, meters, photons, PSheader, line, foundBlank, point14, my_string, InvalidInput

    Note that names are case sensitive, so InvalidInput is not the same as invalidinput.

Variables, Expressions, and Statements (cont.)

  • Statements are units of code that the Python interpreter can execute, like the series of assignment statements from a couple of slides back.
     
  • Operators are symbols that represent computation. Some common ones are +, -, *, /, and ** (the last one means exponentiation). You can use these in expressions to combine values and variables, for example:
    • answer = pi * 100
    • radians = degrees / 360 * 2 * pi
    • fraction = 59 / 60

Python 2 vs Python 3

How integer division is done is the biggest difference between Python 2 and Python 3. When you divide integers in Python 2, Python performs "floor division" and any remainder is discarded. So in the last example...
fraction = 59 / 60
The value of fraction is 0. In Python 3, the result of integer division is of type float, and thus the value of fraction would be 0.9833333.
 
If you're using Python 2 and want integer division to yield fractional results, then you have to ensure that either the dividend or divisor is of type float...
fraction = 59. / 60
If you're using Python 3 and want floor division, then you need to use the // operator...
quotient = 59 // 60

Precedence

When expressions are evaluated, the order of evaluation depends on precedence of the operators. Here are the rules for the mathematical operators:
  • Parentheses have the highest precedence and can be used to explicitly control the order of evaluation.
  • Exponentiation has the next highest precedence.
  • Multiplication and Division have the same precedence and come next.
  • Addition and Subtraction have the same precedence and come next.
  • Operators of the same precedence are evaluated left to right.

Precedence Examples

1 + 1 ** 5 - 2          <== evaluates to 0
(1 + 1) ** (5 - 2)      <== evaluates to 8
6 + 4 / 2               <== evaluates to 8
degrees / 2 * pi        <== is different than... 
degrees / (2 * pi)

To explicitly control how expressions are evaluated just use parenthesis

Python Operators
in increasing order of precedence

Operators Description
x or y Logical ‘or’ (y evaluated only if x is false)
x and y Logical ‘and’ (y evaluated only if x is true)
not x Logical negation
<, <=, >, >=, = =, <>, !=, is, is not, in, not in Comparison operators, identity tests, sequence membership
x | y Bitwise or
x ^ y Bitwise exclusive or
x & y Bitwise and
x<<y, x>>y Shift x left or right by y bits
x + y, x - y Addition/concatenation, substraction
x * y, x / y, x % y Multiplication/repetition, division, remainder/format
-x, +x, ~x Unary negation, identity, bitwise complement
x[i], x[i:j], x.y, x(...) Indexing, slicing, qualification, function calls
(...), [...], {...}, "..." Tuple, list, dictionary, conversion to string

Mixing numeric types

What happens if you mix numeric types in expressions?
a = 3.14159
b = 5
c = a + b
What numeric type is "c"?
 
In this example it's a float. That's because Python converts operands of different types to the type of the "most complex operand" and then evaluates the expression. Since "a" is a floating-point number and "b" is an integer, "b" is converted to a float, then the addition is performed, and then the result (also of type float) is stored in the variable "c".
 
Python ranks numeric types in increasing order of complexity:
  1. Integers
  2. Long integers
  3. Floating-point (float)
  4. Complex numbers

The main exception to this rule is integer division. Python 2 follows the rule and produces an integer result. Python 3 will produce a floating-point result (because division does not always have integral answers).

Operations on non-numeric types

Python tries to do rational things with operators even when it may at first not seem obvious. For example, a few of the "mathematical" operators also work on strings:

  • "first" + "second" performs the concatenation operation and results in the string "firstsecond"

  • "first" * 3 performs repetition and result in the string "firstfirstfirst"

Python Development Environments


 
You'll need to decide on what type of environment you want to do your program development in. In class we'll usually work through examples using a traditional Unix/Linux environment, but there are alternatives.

Development Environments (cont.)

  • In a traditional development environment the programmer uses a "plain" text editor such as Vim or Emacs to write and modify their Python programs. (Microsoft Word won't do, as it inserts all sorts of formatting and font data into your files which Python won't know what to do with.) Programs are then run from the Unix/Linux command line via the Unix shell. The shell provides all sorts of short cuts and tools to make your life as a programmer easier.
     
  • Alternatively you can use IDLE, the standard Python development environment. Its name is an acronym of "Integrated DeveLopment Environment" and it works well on both Unix and Windows platforms. IDLE has a Python interpreter "shell" window, and also has a simple file editor that lets you create and edit existing Python source files. This web page describes how to access IDLE on OS X, Windows, and Linux.
     
  • [short demo in class of vim, the Unix shell, and IDLE]

Functions

A function is just a named sequences of Python statements. You define a function and then later you can call that function. Here’s an example:
def MyFunction():
    print("hello world")
    pi = 3.14159265
    print(pi)
To call this function, you just refer to it by name (but you must include the parentheses)...
MyFunction()
Functions can take arguments, which are objects that are passed to the function when it's called. And functions can return values back to the caller.
def MyOtherFunction(arg):
    ans = (arg + 7) * 10.0
    return ans

x = MyOtherFunction(5)
print(x)    <=== prints 120.0

Functions (cont.)

  • Functions are great for packing up chunks of code into manageable pieces that are easy to understand and can be used (i.e. called) from more than one place in a program. They make your programs easier to write and debug as small units and then combine together into something much bigger that accomplishes the overall desired task.
  • Python has several built-in functions. The most commonly used ones are int(), float, and str():
    • int() takes any value and converts it to an integer.
    • float() converts an integer to a floating point number.
    • str() converts numbers to strings.
  • Python also has a math module that you can import into your program. It defines many mathematical functions. Go to the www.python.org web site and type "math module" in the search box to see all the functions available.

Functions (cont.)

  • Functions allow for code reuse (sections of code to be packaged together and then used in more than one place and more than one time) and for procedural decomposition (splitting large pieces of code into smaller, more manageable chunks).
  • Syntax:
    def function_name(arg1, arg2, ... argN):    # header line
        statements                              # function body
        statements                              # function body
        return some_expression                  # end of function
    
  • Notes:
    1. "def" creates a function object and assigns it to a name.
    2. The "return" statement is optional. If included, it sends a value back to the caller of the function. If not included, the special object "None" is returned to the caller. (The None object is just an empty placeholder.)
    3. All names assigned inside a function are local to that function and exist only while the function executes except when you specify a name in a "global" statement.
    4. Arguments (also known as "parameters") are passed to functions by assignment (object reference). The caller and the function share these objects.

Function Example

def printProduct(i, j):
    print(i * j, end=' ')    # "end" replaces newline character with space

def printRow(n):
    for i in range(1, 10):   # this is a "for" loop (more about this in week 3)
        printProduct(i, n)   # call function printProduct 10 times
    print()                  # start a new line

def printTable():
    for i in range(1,10):
        printRow(i)

printTable()	# function printTable must be defined before here
Output:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18 
3 6 9 12 15 18 21 24 27 
4 8 12 16 20 24 28 32 36 
5 10 15 20 25 30 35 40 45 
6 12 18 24 30 36 42 48 54 
7 14 21 28 35 42 49 56 63 
8 16 24 32 40 48 56 64 72 
9 18 27 36 45 54 63 72 81
(This output could be made to look much nicer using a formatted print statement which we'll cover in week 3.)

Python 2 vs Python 3

The other major difference between Python 2 and Python 3 is the print statement. In Python 2, print is a statement...
print i * j
But in Python 3 print is a function call...
print(i * j)

 
The biggest impact this has is when supressing new lines. The example on the previous slide must change to the following in Python 2:
def printProduct(i, j):
    print i * j,             # the comma suppresses a new line after each number

def printRow(n):
    for i in range(1, 10):   # this is a "for" loop (more about this in week 3)
        printProduct(i, n)   # call function printProduct 10 times
    print                    # start a new line

Homework

  • 1.1 - Compute the volume of a sphere
  • 1.2 - Write some functions

  •  
  • You should turn in one source file that addresses both assignments and includes all the required functions and code that tests those functions. As long as you put the function definitions first in the file, any subsequent Python code is then able to call those functions. Then email the file as an attachment to pc204@cgl.ucsf.edu