# notmuch.py by chaynes@indiana.edu
print "Not much of a program, but it's Python!"
This program just prints a message, and starts with an identifying comment
We will analyze this shortly, but first the big picture
Python programs: The big picture
A Python program is a sequence of statements in a plain text file
A plain text file contains only "plain" characters that you type at the keyboard
plain text files often have the suffix .txt, but Python uses the suffix
.py
.doc and other document file types are not plain text
A program may include collections of code, called modules, imported from other
files
in this course you will only be importing modules that are given to
you, usually in the standard Python library
How can I create Python programs?
Any plain-text editor may be used to create or modify a Python program
Word and other document editors can usually save files in plain-text
form, but they mess up formatting: don't use them for Python programming!
Python comes with IDLE: an Integrated DeveLopment Environment
that includes:
a plain-text editor (script windows) that provides colorizing and
indentation to help with Python syntax
an interactive (shell) window
a debugger that can help you understand the execution of programs
The RUR-PLE Python environment, which you will be using at least
initially, also has a Python-aware editor and interactive shell
it does not have a debugger, but does have a unique robot simulation environment
Ways of running Python programs
In an IDLE editor window, pressing F5
In RUR-PLE, clicking the green Run button in the editor or the robot
windows
In an operating system command shell, with a python command
In many systems, just double-click the program file in a file explorer
normally an output window opens, and closes when the program ends
Many other possibilities, such as:
cgi scripts, invoked by a web server in response to a web browser request
scripts automatically invoked by the operating system at specified times
Some cool places Python is used
Nokia 6630 smarthphone
One Laptop Per Child project $100 computer
iPod, Palm, Pocket PCs
This course's web site and administrative tools
What kinds of programs can I write?
The syntax of a language determines whether a sequence of characters is a
legal program
Syntax is specified in terms of a few general rules about comments and
whitespace and a number of rules that define the language's syntactic
forms (forms that syntax can take)
in natural languages, these are "parts of speech" such as noun, verb,
noun phrase, sentence
computer language examples: statement, expression, function call,
variable reference
What does a program do?
The semantics of a programming language determines what a program will do
For each syntax rule we cover, you need to learn the corresponding
semantics: the meaning of program elements corresponding to the rule
To know what a particular program does, you first have to know its
syntactic structure, and then trace or reason about the program based on
the meaning of each part of its structure
Sublanguages
In this course you will be learning only part (perhaps half) of the
syntax of the full Python language
but this includes most of the commonly used syntax
Syntax rules, and corresponding semantics, will be introduced one at a time
We will use only a very small part of the functions and classes that are
built in or available in the Python libraries
no one learns them all: when they are needed programmers look up
language features that they do not used often in documentation
Python syntax: comments and whitespace
Comments begin with the character #
Python ignores everything from the # character (pronounced "hash" by
hackers) to the end of the line
# in Python is similar to // in Alice
Whitespace refers to space, tab, newline, and return characters
generally avoid tabs (since they are interpreted inconsistently)
Blank lines, tabs, and spaces in Python programs are generally ignored
unless they in a string or part of line indentation
use them to group related statements and parts of expressions
whitespace is not allowed in names, keywords, or multi-character operators (like **)
Statements and expressions
The two most important syntactic forms are expression and
statement
most of the syntax rules define a possible form of expression or statement
Running, or executing, a program involves executing its statements in
a specific order
If a statement contains an expression, when the statement is
executed, the expression is (usually) evaluated
Example: the notmuch.py program contains one statement, which prints
some output, and this statement has one expression, a "string" that
contains the characters to be printed
Statement execution
A statement is executed for some effect it has on the runtime environment of
the program
examples: assigning a variable, printing some characters, or changing some
graphics
what a statement does may depend on the values of one or more
expressions contained in the statement
Some statements contain other statements, called nested statements
the form of a statement, and the runtime environment, determines
whether, and in what order, its nested statements are executed
The same statement may be evaluated many times when its program is run,
and the effect may be different each time, for it depends on the ever-changing
runtime environment
Expression evaluation
Usually the only effect of evaluating an expression is to yield some value
Expressions often contain other expressions, called sub-expressions
before an expression itself is evaluated, all of its sub-expressions are
evaluated (with one exception)
what, if anything, is done with the value is determined by the statement that
contains the expression
Some expressions contain function calls that result in "side" effects to
the runtime environment, in addition to returning a value
The same expression may be evaluated many times in a program run,
and its value (and side effect, if any) may be different each time
in words: the syntax of a print statement is the characters print (in
this case a "keyword"), followed by a space, and then a sequence of
zero or more expressions separated by commas
Python is almost always case sensitive: whether a character is upper or lower
case matters
example: if you type Print instead of print, an error will result
Semantics: evaluate each expression and print their values, separated
by a single space, followed by a newline character (end the current line)
any value may be printed, though printed representations of some values
may not be meaningful
string values print without surrounding quotation characters
Examples:
>>> print "I am Arthur, king of the Britons."
I am Arthur, king of the Britons.
>>> print 1, "plus", 2, "is", 3
1 plus 2 is 3
Literals
Expression syntax rule: an expression may be a literal
Semantics: the value of the expression is given by the "literal" text of
the expression
Examples: strings and numbers
Strings literals (simplified)
Expression syntax rule: a string literal is sequence of characters on
the same line beginning with a double quote ("), ending with a double
quote, and not containing a double quote or backslash (\) character
Examples: "@$%SPAM#!&EGGS", and the print statement expression in
notmuch.py
note that any keyboard character character, other than double quote,
backslash and newline (Enter), is allowed in a string, and they are
all significant (including multiple spaces)
Interactive demo: Numbers
>>> 1 + 1
2
>>> 1.2 * 3.4
4.0800000000000001
>>> 2 / 3.0
0.66666666666666663
>>> 2/3
0
>>> 2 ** 8
256
>>> 2**30
1073741824
>>> 2**31
2147483648L
>>> 2**2000
1148130695274254524232833201177681984022317702088695200477642736825766261392370\
3138566594863165062699184459646389874627734471189608630553314259313561666531853\
9129989145312280000688779148240044871428926990063486244781615463646388363947317\
0260404663539709049965581623988089446296056233116495361642219703326813441689089\
8445850560237948480791405890093477650042900271670662583052200813223628129176126\
7883317206598995396418127021779858404042159853183251540889433902091920554957783\
5896720391600819572166305827553804255837260155283487864194320545089152757838826\
25175435528800822842770817965453762184851149029376L
>>> 2.**2000
Traceback (most recent call last):
File "", line 1, in ?
OverflowError: (34, 'Result too large')
>>> 2.**1000
1.0715086071862673e+301
>>> -1 - +2
-3
>>> -(1-2)
1
>>> 1 + 2 * 3
7
>>> 1 + (2 * 3)
7
>>> (1 + 2) * 3
9
>>> 8 / 4 / 2
1
>>> 8 / (4 / 2)
4
>>> (10 + 5) % 12 # 10 o'clock plus 5 hours is 3 o'clock
3
>>> (275 + 120) % 360 # from a heading of 275 degrees, turn right 120 degrees
35
>>> ((1 + 2) / 3)) + 4
File "", line 1
((1 + 2) / 3)) + 4
^
SyntaxError: invalid syntax
>>> 8 / (1 / 2)
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: integer division or modulo by zero
>>> l+2
Traceback (most recent call last):
File "", line 1, in
NameError: name 'l' is not defined
>>> None
>>>
Interacting with Python
An interactive shell window is a
great way of running little bits of Python interactively
as in the IDLE shell, the RUR-PLE "Python: Code and Learn" shell
window, or an operating system window running the python command
In a shell, you interact with a simple program that does the following in an
infinite loop:
prints the prompt >>>
reads a statement or expression you type and executes it
displays any program output (and may accept keyboard input)
prints the value returned, unless it is None
The shell allows you to use variables
Take advantage of the shell -- it's fun and easy :)
The shell is great for experimenting with program elements
If you are wondering how some bit of Python works, it is often faster to
run an experiment in the shell than look up the answer in documentation
Not good for writing programs
you cannot easily save or edit code written in a shell
Kinds of errors
Syntax errors: detected before the program runs
they keep the program from running
a message is printed with the error type and location (both of which
may be misleading)
Runtime errors: when the program runs ("at runtime")
if they are detected by the system, a Traceback message is printed
indicating the kind of error and where it occurred
traceback information may not reflect the actual program error, since
errors are not always detected where they occur
other runtime errors may not be detected, for example
infinite loops
the program follows the rules of Python, but may not do
what it is supposed to
Syntax error messages can be misleading
The program:
print ("missing right paren on this line"
print "error reported on this line"
results in the messge:
File "", line 3
print "error reported on this line"
^
SyntaxError: invalid syntax
even thought the error is on line 1.
fix it by either removing the open
parenthesis from line 1, which is unnecessary, or add a closing parenthesis
at the end of line 1.)
The position of an error report is always where the error was detected, not
where the actual error in the program is located.
Types
Every value in Python has a corresponding type
The type of a value determines the operations are allowed to be used on it
A runtime error results if the type of value is not acceptable to an
operation that is attempted with the value
this prevents operations that do not make sense, like adding a number
to a string
of course you can still perform operations that do not make sense for
other reasons
FYI: Languages such as Python that detect type errors at runtime are said to
be "dynamically typed" or "scripting" languages
some languages detect type errors at "compile time" before they are
run, but these languages require a type system that is very
complicated, like Java's, or very limited, like Alice's, making them
most suitable for professional programmers or beginners, respectively
Numeric types in Python
int: mathematical integers that are not too big
literal values do not have decimal points
completely accurate
converted to the other integer type, long, if they get too big
float: fractional values
"floating point" numbers because they have a decimal point that is
automatically positioned
may have an exponent (scientific notation)
exponent follows the letter e
used to express numbers with up to several hundred digits before or
after the decimal point
accuracy limited to 17 decimal place
usually not all digits are significant
Python number types not used in this course (but which might appear due
to program errors):
long: very large integers (unlimited in size), which end with the letter L
complex: mathematical "complex numbers", which end with the letter j
Common mathematical operators
Some common mathematical operators:
+ addition
- subtraction
* multiplication
/ division
if both division operator arguments are integers, the quotient of
integer division is returned
the remainder is then discarded
this is generally equivalent to truncation (throwing away
digits after the decimal point) of the
corresponding floating division result, but yields an integer result
% remainder
** exponentiation: a**b is a raised to the power b
Remainders
% (percent sign) is the remainder operator
same as the modulus operation if both arguments are positive
The modulus operation is very useful for computations involving
"cyclical" data, such as the 12 hours on a clock or 360 degrees on a compass
>>> (10 + 5) % 12 # 10 o'clock plus 5 hours is 3 o'clock
3
>>> # from a heading of 275 degrees, turn right 120 degrees
>>> (275 + 120) % 360
35
Unary operators
The above are binary operators that appear between their operands
(argument expressions)
The unary operators + and - only have one operand, which they precede
example: -(3-1)*+5
Numeric type conversion
If both arguments of a binary numeric operator are of the same type, the
result has the same type
If one operator argument is an integer and the other a floating point:
the integer is automatically converted to floating point
the result is a floating point number
Example: 3*2.2 ⇒ 6.6
Evaluation
Read ⇒ as "results in"
Informally ⇒ may be read as "is", but it is important to
keep in mind the difference between an expression and its value
The process of computing the value of an expression is called
evaluation, so more formally ⇒ means "evaluates to"
What operation comes first?
In the expression 2+3*4, is the addition or multiplication
operation performed first?
answer: multiplication, as in mathematical usage
Operator precedence rules determine the order of operations
"precedence" here means "priority"
Operator precedence
Operators with higher precedence are done before those with lower
precedence
Operators we have seen so far, from high to low precedence (those on the
same line are of the same precedence):
function call
unary +, unary -, **
*, /, %
+, -
Chains of operations of the same precedence are performed left to right
example: 8/4/2 is equivalent to (8/4)/2, not 8/(4/2)
These precedence rules follow common mathematical usage and are used in
many computing contexts such as spreadsheet expressions
Parenthesized expressions
Parenthesis may be placed around any expression
This is usually done to force a different order of evaluation
example: 2*(3+4) ⇒ 14
not the same as 2*3+4 ⇒ 10
Use parenthesis whenever someone reading the program may be in doubt about the
precedence of operations in an expression
Using clicker numeric keys, ., and -, what is the value of the following?
Enter zero if a syntax or runtime error will result.
Use the SYM key to the right of the zero key to enter a decimal point.
1+2**3
Answer: 9
2.*-2
Answer: -4.0
1/(2*3
Answer: 0
-((4))
Answer: -4
8/4*2
Answer: 4
1/3*3
Answer: 0
1+10%3
Answer: 2
0/0+1
Answer: 0
Programming language expressions are NOT mathematical expressions
Some algebraic equations are true for programming expressions
for example a*(b+c) equals a*b+a*c, when a, b, and c are integers
slightly different results are possible with floating point numbers
Others algebraic equations do not hold
for example (1/3)*3 ⇒ 0, not 1
(1.0/3)*3 ⇒ 1.0 in the current Python implementation, but
might be slightly different in another implementation
Interactive demo: Variables
>>> x = 3
>>> x
3
>>> x = x + 1
>>> x
4
>>> x += 1 # same as x = x + 1
5
>>> x *= 2 # same as x = x * 2
10
>>> first_name = 'Humpty'
>>> first_name
'Humpty'
>>> First_name
Traceback (most recent call last):
File "", line 1, in ?
NameError: name 'First_Name' is not defined
>>> 1st_name = 'Alice'
File "", line 1
1st_name = 'Alice'
^
SyntaxError: invalid syntax
>>> first name = 'Alice'
File "", line 1
first name = 'Alice'
^
SyntaxError: invalid syntax
>>> firstName = 'Alice'
>>>
Python names
Names are also identifiers, because they are used to identify variables,
functions, methods, modules, and classes
Names may contain only
upper or lower case letters (A to Z and a to z)
underscore (_)
digits (0 to 9), but not as the first character of a name
Names are case sensitive
upper and lower case versions of the same letter are completely different
Names may not be keywords
the Python keywords are: and,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,in,is,lambda,not,or,pass,print,raise,return,try,while,yield
keywords are colored orange in the IDLE editor and blue/gray in the
RUR-PLE editor
Name conventions for good style
Compound names
underscore-separated, as in get_value
camel case, as in getValue
run-together lower case, as in getvalue
bad style, except for module names, which generally use only lower
case
Names start with lower case letters, except
all-caps, sometimes used for constants, as in F_OK
class names, not used in this course, start with upper case letters
Use either camel-case and underscore-separated throughout a program
Python does not care if your programs have good style, but bad style
makes your programs harder for you and other humans to read
Use descriptive names
Use very short names only when all uses are within a few lines and the
meaning is obvious
i, j, n, and m are commonly used for integers
x and y commonly used for floating point numbers
Avoid very long names (over about 15 characters)
Variables
A variable is a location in memory that has a name and contains a value,
and may be assigned new values
A variable reference (use of its name) is a form of expression that
returns the value in the variable
variables must be assigned before they are referenced
A variable assignment is a form of statement (and hence does not return
any value)
syntax: variable_name=expression
semantics: assign the value of expression to the named variable
if there isn't a variable with the given name, a new variable is created
otherwise, the value in the existing variable is replaced with the
new value (and the old value is lost)
Augmented assignment statements
The augmented assignment statements, using +=, -=, *=, /=, and %=
combine an operator and assignment
the left-hand argument must be a variable
the augmented assignment characters sequences above are not operators
(contrary to the text)
Example: x+=3 is equivalent to x=x+3
Avoid using augmented assignments if you find them at all confusing, but
learn to read programs that use them, because they are common in lots of
languages
What is printed by this statement?
print "1 + 3"
"1+3"
4
1+3
Which of the following is not a legal variable name?
velocity_in_meters_per_second
velocityInMetersPerSecond
velocity_meters/sec
velocityinmeterspersecond
velocity2
C and D
A, C, and D
Answer: F
What is the value of x after the following statements?
x = 3
x = x + 6
x /= 2
(Use your clicker number pad.)
Answer: 4
What is the value of b after the following statements?
a = 3
b = a
a = 4
(Use your clicker number pad.)
Answer: 3
How NOT to think about variable assignment
Variable assignment is not a test of the variable's value or a
declaration that the variable's value will always equal the indicated value
it makes them equal at the time of assignment, but subsequent variable
assignments may change the value of the variable or the value
of the expression
as illustrated in the last question above
This is unlike the common usage of = in mathematics as a
declaration of equality
Warning: falling out of our sublanguage can be confusing
If you make a syntax mistake, it will usually result in a syntax error, but not
if you have accidentally fallen into an advanced form of syntax
Error messages may then seem strange
example: suppose you mean to say (x+y)/2, but you make the
mistake of using square brackets instead of parenthesis, as in [1+2]/3, you will get a message TypeError:unsupportedoperandtype(s)for/:'list'and'int' because square brackets make lists, which is
very confusing if you haven't learned about lists yet
You may get the wrong answer, without any error message
example: print(4,5) prints (4,5), not 45
example: print1,001+2 prints 13, not 1003
example: 2^3 ⇒ 1, not 8
in some languages ^ is the exponentiation operator, not ** as in
Python and some other languages, but in Python ^ is
an operator that does something else that is not used in
this course ("bitwise or")
Python comes with a number of functions stored in built-in variables
that are defined when the system starts up
unlike keywords, most built-in variable names can be used for other
purposes, so you don't have to be aware of them all
For every "primitive" type there is a type function named after the type that
takes one argument and converts it to the type if at all possible
so far we have seen the type functions int and float
truncation is used in float to int conversion
The built-in function round takes a float and rounds it to the
nearest integer, rather than truncating, but still returns a value of
type float
Most functions and classes (with their methods) that come with Python
are provided in library modules, instead of being built-in
Reeborg the robot programming
The robot control and repeat functions used for programming Reeborg the robot
programming are only built-in for programs are run in its RUR-PLE "Robot: Code
and Learn" tab
Introduced in lab this week
In this week's assigned reading
Ignore the built-in functions id and type introduced on page 21 of
the Python text
id is very seldom used
type is obsolete
Not covered this week, but soon
str function in section 3.2
math module use and import statements in sections 3.4 and 3.5
What kind of function calls are possible?
Can function calls be nested, as in int(float(x)/3) ?
Yes
How many arguments are possible?
Any number, including zero, as long as the function being called
allows that number of arguments
What about spaces in a function call? Is f(x,y) the same as f(x,y) ?
Yes
Do I have to learn lots of special facts like this?
No, you have to learn a much smaller number of general syntax rules
Function call syntax
Function call expression syntax:
function_expression(expression,...,expression)
expression,...,expression is a comma-separated sequence of
zero or more expressions, whose values are the arguments of the call
function may be any expression, but it is almost always the
name of a function (or more precisely, a reference to a variable that
contains a function)
Notation for grammar rules
Syntactic forms and arguments are in a slanted bold font
for example, function and expression
Literal elements are in the codefont
for example, def and the parenthesis and commas
in the function call syntax
Ellipsis indicates zero or more of the surrounding forms
for example: form,...,form indicates zero or more instances of form
separated by commas
in contexts other than syntax rules, ellipsis usually indicates where
text has been deleted
Square brackets enclose optional elements (example soon)
These conventions are common, but there are many notational variations used
in different documentation
Function calls as statements
A function call is a kind of expression
An expression is also a kind of statement
So a function call may appear as a statement
in which case the value returned by the function is thrown away
A function call is the only form of expression that makes sense as a
statement, and then only if the functions performs some kind of side
effect (has some effect "on the side" in addition to returning a value)
Text error
On page 21 of the text, the repeated statement that an argument may be a
value or variable is wrong
An argument may be any value, and is frequently the value stored in a
variable, but (in Python and most languages) variables themselves are
never values
for example, in the call int(x) of the previous demo, the argument is
-5.7, which is the value of x, but not the variable itself (using the
box analogy, the argument is what is in the x box, not the box itself)
each of the zero-or-more parameters is the name of a variable
A block (here also called the functions "body") begins on a new line and is
indented
Blocks and indentation
In general, a block is one or more statements, all indented by the
same amount and more than the line that precedes the block
the line preceding a block always ends in a colon
the IDLE's default indentation of 4 characters is best
much less (1 or 2) is very hard to read
much more (such as the 8 characters usually associated with tabs) often
results in lines that are much too long (over 80 characters) when
blocks are nested, as often happens
In Python, consistent indentation is critical
in most programming languages, consistent indentation is necessary for
readability, but the system does not care
by being picky about indentation (about which you should be picky
anyway) Python avoids the need for extra syntax to indicate where
blocks end
Function definition semantics
Create a function with the given parameters that executes the body block
when the function is called (invoked)
the block is not executed when the function is defined
This function is assigned to the variable function_name
Assignments within functions
Without additional syntax, variables assigned in a function body cannot be referenced
outside the function body
Example:
x = 3
def f():
x = 4
f()
print x
prints 3, not 4, since the assignment within the function creates a new
variable local to the function.
Function call semantics
Function call semantics (what it does):
evaluate the function and argument sub-expressions
associate the arguments with the corresponding function parameters
more precisely: parameters are variables that are created when the
function is called, assigned the value of the corresponding argument,
and destroyed when the function returns
execute the function body
return control to the point in the program from which the function was
called
the value "returned" by the function is the value of the function call
Python functions and methods
In Python, a method is a particular kind of function associated with a class
Python functions (including methods) return values and may perform actions
If a function call does not end with a return statement (covered next
week), the value None is returned
Function and method calls are a kind of expression, since they return
values
Since calls may also perform actions in Python, an expression is one
kind of statement
Unlike Alice, which makes clear function/method and expression/statement
distinctions
What does the following program do?
def f():
g()
def g();
print "we eat ham and jam and spamalot"
f()
prints we eat ham and jam and spamalot
syntax error
runtime error
it depends on the implementation
Answer: A
What does the following program do?
ham = spam
spam = "a lot"
print ham, spam
prints a lot a lot
syntax error
runtime error
Answer: C
Alice practical test
In the first hour of lab this week
Open book and open notes
Tests
About five 30 minute tests will be given in class at unannounced times, possibly
starting next week
lowest non-excused test grade is dropped
Tests only Python material through the previous week
Peer Tutoring reminder
Every Monday, 7:15-10:15 PM, in LH115
Undergraduate students who have recently taken this course are there to
help you
Refreshments provided
Computers available for your use
Informal atmosphere ☺
the tutors have no connection with course grading
See the updated Syllabus page for a bit more information