The pass statement in Lesson 14 is left out of the course's
Python Syntax summary
since it is non-essential (you could for example use the string "pass"
instead).
If the program is run with F5 in the IDLE, interactive input and output
are displayed in the IDLE shell window
Program code:
# celsius2.py, by chaynes@indiana.edu
# Prompt for tempearture in degrees Fahrenheit and print its conversion to degrees Celsius.
fahrenheit = int(raw_input("Degrees Fahrenheit: "))
celsius = 5.0/9 * (fahrenheit - 32)
print fahrenheit, "degrees Fahrenheit is", celsius, "degrees Celsius"
Interactive character (shell) input
The built-in function raw_input(prompt) prints the string
prompt, without a newline, and returns the next line of user input
the program blocks (stops) until the user enters a newline (presses
the Enter key)
always returns a string
best if prompt ends with a space
Do not use the related function input
it evaluates the input string, which can be tricky
Other temperature conversion program notes
It is necessary to convert the input string to a floating point number
before doing mathematical operations with the number
more on this in a moment
Using 5.0 instead of 5 prevents the truncation of integer division
print command subexpressions may be of any type: they are automatically
converted to strings
recall that in the output spaces are inserted between the subexpression
strings
Textual User Interfaces
The simplest kind of program input and output just uses sequences of text characters
such character sequences are known as plain text, to distinguish them
from text that includes formatting instructions
all that is needed is a keyboard for text input and some way of
displaying plain text output
Such programs are said to have a Textual User Interface (or TUI, to coin
a non-standard acronym)
The common alternative today are programs with Graphic User Interfaces (the common
acronym is GUI)
these require graphic displays and usually both mouse and keyboard
input
GUI vs. TUI
TUI advantages
programs with TUIs are generally much easier to write than programs
with GUIs
it is relatively easy to combine TUI programs, with the output of one feeding the
input of another (they make great building blocks)
TUI interaction can be very efficient, if you know what you are doing
a TUI is very portable (runs with little or no change on a variety of systems)
GUI advantages
complex interaction possibilities can be presented in an intuitive way
that requires little documentation or memorization to use
the mouse allows dynamic interaction possibilities that keyboards don't
Bottom line: TUIs are better when either
the program is not used enough to justify the work of building a GUI interface
users are experienced and want to combine or automate program execution
Shell Scripts
Almost all operating systems come with a TUI program for running other
TUI programs, called a shell
"shell" is an old term that indicates the interface between the
O.S. innards and the user
like the IDLE shell, an O.S. shell is an infinite read, evaluate (or run), and then
print loop
in the early days, this was often the primary or only way of
interacting directly with a computer
there are still many operations that are only designed to be used this way
Programs written in dynamically-typed languages such as Python are often
called scripts
Scripts intended to be invoked from shells are called shell scripts
interactive input is via the keyboard and interactive output is via
printed characters (as with the print statement)
instead of or in addition to interactive I/O (Input/Output), shell scripts may also
use file I/O, which often also involves only plain text
Interactive demo: simple strings and the print statement
::
>>> 3
3
>>> print 3
3
>>> 'this is a string'
'this is a string'
>>> print 'this is a string'
this is a string
>>> print 'The answer is', 1+2
The answer is 3
>>> print 1, '+', 2, '=', 1+2
1 + 2 = 3
What is printing?
What happens to printed characters depends on how the program is run
Programs run in the IDLE or operating system shell display printed
output in the shell window
The interactive python shell also displays the values of expressions
entered at its prompt (unless the value is None)
recall that some values, such as strings, are displayed differently by print
statements and the shell
Your text's statement, on page 14, that "the result of a print statement
is a value" is incorrect.
the "result" is that some characters are output, and may be displayed
somewhere, but such output is not a python value
Demo: more fun with type functions
>>> int('3')
3
>>> int('1+2')
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: '1+2'
>>> float(' 3.14159 ')
3.1415899999999999
>>> str(3.14159)
'3.14159'
>>> str(1 + 2)
'3'
Type functions revisited
str is the name of the string type, and its built-in conversion
function, which converts any value to a string representation
The int and float type functions take parse strings into values of
their type
they raise an error if the string does not represent a number of the
right type (float will convert integers to floating point)
leading and trailing white space is stripped off (removed)
Example: abstracting behavior
We note that the code in the celsius2.py program can be organized into two
primary elements
the actual Fahrenheit to Celsius conversion, which is a general
functional transformation
the specific behavior of the program: prompt for the temperature, do
the conversion, and print the result
main is the traditional name for a function that performs the overall
program behavior
We refactor (reorganize for better style) the code into two functions,
followed by a call to the main function, which initiates program
behavior
we also introduce two local variables in the main function
# celsius3.py, by chaynes@indiana.edu
# Prompt for tempearture in degrees Fahrenheit and print its conversion to degrees Celsius.
# return the result of converting the Fahrenheit temperature to celsius
def celsius(fahrenheit):
return 5.0/9 * (fahrenheit - 32)
def main():
f_temp = float(raw_input("Degrees Fahrenheit: "))
c_temp = celsius(f_temp)
print f_temp, "degrees Fahrenheit is", print c_temp, "degrees Celsius"
main()
return statement
Syntax: return [ expression ]
this statement may only be used in a function (or method) body
the square brackets indicate the expression is optional
Semantics:
expression is evaluated and its value is returned as the value of the
the current function call (the one that caused the body of the current
function to be executed)
if expression is omitted, the value None is returned
control returns immediately from the current function, without
executing any more code in the function body
If execution of a function body completes without execution of a return
statement, None is returned
Demo: printing is not returning
>>> def print_three():
print 3
>>> def return_three():
return 3
>>> return_three() + 1
4
>>> print_three() + 1
3
Traceback (most recent call last):
File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> print return_three()
3
>>> print print_three()
3
None
>>>
Printing vs. returning
A function that prints a value is very different from one that returns a value
a function could do both, but that is generally bad style
functions that do printing and other actions with "side effects"
generally do not return values (or in Python they return None)
Calls to functions that return None only make sense when the call is
a statement
when a function call is a statement, the value returned is thrown away
Which is probably better for a simple program that only you will use?
A graphic user interface
A textual user interface
Neither, they are about the same difficulty to implement
Answer: B
If a function is supposed to return a value it computes
it must contain a return statement
it must contain a print statement
it may contain either a return or a print statement
it must contain both a return and a print statement
Answer: A
What does the following program do?
def f():
print 3
f
There is a syntax error, so the program does not run
The program runs, but does nothing
3 is printed
Answer: B
Demo: forever temperature conversion service
# celsius4.py, by chaynes@indiana.edu
# Repeatedly prompt for tempearture in degrees Fahrenheit
# and print its conversion to degrees Celsius.
# return the result of converting the Fahrenheit temperature to celsius
def celsius(fahrenheit):
return 5.0/9 * (fahrenheit - 32)
def main():
while True:
f_temp = float(raw_input("Degrees Fahrenheit: "))
c_temp = celsius(f_temp)
print f_temp, "degrees Fahrenheit is", print c_temp, "degrees Celsius"
main()
Infinite loops
Syntax: whileTrue:body_block
Semantics: repeatedly execute body_bkock, forever
"forever" really means until program control is somehow told to leave
that part of the program, or the program is terminated
if the loop is in a function, we already know one way to tell control
to leave: return
Ways of killing programs
Programs can usually be killed by typing control-C, which sends a
keyboard interupt
sometimes this needs to be repeated a few times
If that does not work, IDLE programs can usually be terminated with the
Shell>Restartshell menu command
Most programs can be killed by closing their interaction window (using
the upper-right x box in Windows)
If that fails, you can generally use an operating system task (or
process) management utility to kill the program
Start>run>taskmgr starts the Windows task manager, with a GUI
interface for killing applications and processes, among other things
Demo: string literals, docstrings, and help
>>> print 'The Knights said "Ni"'
The Knights said "Ni"
>>> print "That'll do"
That'll do
>>> s = """This is a multi-line
... string with
... three lines"""
>>> print s
This is a multi-line
string with
three lines
>>> min(2, 3)
2
>>> min
>>>
>>> help(min)
Help on built-in function min in module __builtin__:
min(...)
min(iterable[, key=func]) -> value
min(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its smallest item.
With two or more arguments, return the smallest argument.
>>> def middle(x, y, z):
... """
... Of the three values that are given,
... return the one that is between the other two.
... """
... return max(x, min(y, z))
...
>>> help(middle)
Help on function middle in module __main__:
middle(x, y, z)
Of the three values that are given,
return the one that is between the other two.
>>>
String literal syntax
Single-line string literals begin a single or double quote character and
end with the next (un-escaped) occurrence of the same character on the
same line
we will learn about character escaping soon
Multi-line string literals begin with three single or double quote
characters and end with the next (un-escaped) occurrence of the same
characters (perhaps many lines later)
Help is just a function call away
The built-in function help takes any value and tells you about it
sometimes more than you want to know, since there's more to Python than
we use in this course
Give it a function and it indicates its parameters, and what it does (as
indicated by its documentation string, if it has one)
Give it a module (that has been imported), and it tells you what
operations it provides
we'll see modules shortly
With doc strings we can add such documentation to our own functions
Doc strings
If the first statement in a Python file or function body is a string, the
string is retained as documentation, available using the built-in
function help
Multi-line strings (traditionally with double quotes) are often used for
documentation strings
It is often helpful if documentation includes a transcript that
demonstrates some simple tests
Example: temperature conversion program with string documentation
# celsius5.py, by chaynes@indiana.edu
def celsius(fahrenheit):
"""
Return the result of converting the Fahrenheit temperature to celsius.
>>> celsius(32)
0.0
>>> celsius(212)
100.0
>>>
"""
return 5.0/9 * (fahrenheit - 32)
def main():
"""
Repeatedly prompt for tempearture in degrees Fahrenheit
and print its conversion to degrees Celsius.
"""
while True:
f_temp = float(raw_input("Degrees Fahrenheit: "))
c_temp = celsius(f_temp)
print f_temp, "degrees Fahrenheit is", print c_temp, "degrees Celsius"
main()
Module use demo
>>> import math
>>> math.sqrt(4)
2.0
>>> import random
>>> random.random()
0.24550873036853438
>>> random.randrange(10)
5
Modules
Python comes with a library containing many modules
example: math and random
many other Python modules are available on the web
modules are also used to organize programs that are too large to
conveniently fit in one file
Modules must be imported before the functions, classes, and other
values they export can be used
import statement
Syntax: importmodule_name
Semantics:
execute the code of the named module, which is in a file, the name of
which is the module name followed by .py or .pyc ("compiled"
modules)
the module file must be someplace python can find it, which may be
(among other possibilities) in a
standard library or in the same directory as as the importing code
note that the extension .py (or .pyc) is not part of the module name
create an object with attributes (object variiables,
a.k.a. properties) containing the values exported by the module
in the importing program, create a variable named after the module
containing the module object
Semantics: return the value of the attribute in the module or object
module attributes are usually functions, but some are other values,
such as the floating point value math.pi
Module functions introduced this week
math.sqrt(x) returns the square root of x
random.random() returns a (pseudo-)randomly chosen floating point value
between 0 and 1
random.randrange(n) returns a (pseudo-)randomly chosen integer in the
range from 0 to n-1
Conditional evaluation example
# celsius6.py, by chaynes@indiana.edu
def celsius(fahrenheit):
"""
Return the result of converting the Fahrenheit temperature to celsius.
>>> celsius(32)
0.0
>>> celsius(212)
100.0
>>>
"""
return 5.0/9 * (fahrenheit - 32)
def main():
"""
Repeatedly prompt for tempearture in degrees Fahrenheit
and print its conversion to degrees Celsius.
Exit if 'quit' is entered.
"""
while True:
text = raw_input("Degrees Fahrenheit, or 'quit': ")
if text == 'quit':
return
f_temp = float(text)
c_temp = celsius(f_temp)
print f_temp, "degrees Fahrenheit is", c_temp, "degrees Celsius"
if __name__ == '__main__':
main()
Sentinel loops
A sentinel loop ends when a particular input value or condition is
encountered
later we'll see how to use the common End-Of-File (EOF) condition
usually coded using whileTrue with a breaking control statement
(such as return) in the while body when the sentinel is detected
This presumes that main is a function of no arguments that initiates
the behavior desired when the file is run as a program
This mechanism is unique to Python, and is optional in programs you write
in this course
it is used to test many of the programs provided for this course, but
you don't need to be concerned with how it works
if you're curious, the file is run as a subprogram (it is imported
as a module into another program), the main method is not called
Comparison operators
Equality operators:
== equal to
do not confuse with = of assignment statements
!= not equal to
Ordering operators:
> greater than
< less than
>= greater than or equal
<= less than or equal
All comparison operators return boolean values
We saw the same operators Alice, and they are found in most languages
Simple if statement
Syntax:
iftest_expression:
then_block
Semantics:
evaluate test_expression and if it returns a true value, execute the
then_block statements in order
Whenever a block is nested inside another block, the inner block must be
indented more than the outer block
important style: use a fixed amount of additional indentation, 3 or 4
spaces, throughout a program
What's true?
The boolean type bool has just two values, in the built-in variables True
and False
all comparison operators return boolean values
The false values are:
False (preferred)
zero numeric values
None
empty data sructures (strings, lists, tuples, and dictionaries)
All other values are true values
True is the preferred true value
Two-armed conditionals
Syntax
iftest_expression:
then_block
else:
else_block
Semantics
if the value of test_expression is a true value, then execute then_block
otherwise execute else_block
Conditional flow charts
Example: isDivisible
From section 5.4 of your Python text (perhaps a holdover from a very early
version of Python w/o the bool type):
def is_divisible(x, y):
if x % y == 0:
return 1 # it's true
else:
return 0 # it's false
Better style:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
Best style:
def is_divisible(x, y):
return x % y == 0
Exercise: abs function
In mathematics the absolute value of a number n is n if n is positive or
minus n if n is negative
the absolute value is always non-negative
The built-in Python function abs returns the absolute value of its argument:
>>> abs(3.5)
3.5
>>> abs(-2)
2
abs function implementation
Answer A, B, or C if the corresponding function below is a
correct implementation of the abs function, D if they are all correct, and
E if none are correct:
def a(x): def c(x):
if x < 0: if x < 0:
return -x x = -x
return x return x
def b(x):
if x < 0:
return -x
else:
return x
Answer: D
Which function (a, b, or c) has the style you like best?
Answer: I like B best in this case, but they are all acceptable
Which of the following four functions returns the minimum of its two arguments?
def a(x, y): def c(x, y):
if x <= y: if x < y:
x print x
else: else:
y print y
def b(x,y): def d(x, y):
if (x < y): if y > x:
return y return x
else: else:
return x return y
Answer: D
Chained conditionals
Syntax:
iftest_expression:then_block
[ eliftest_expression:then_block ] ...
[ else:else_block ]
the ellipsis (...) indicates zero or more of repetitions of the preceding
two lines, and as usual square brackets mean "optional"
Semantics:
evaluate each test_expression in order until one returns a true value
then execute its then_block and exit the if statement
if all test_expressions return false values execute elseBlock if it is present
Chained conditional flow chart
Using chained conditionals
Use elif whenever the only statement in an else block is another if
statement
this avoids unnecessarily increasing the amount of indentation
use nested conditional statements as needed in any other blocks, such
as a thenBlock
FYI Though block is the term for a sequence of statements in most
languages, in official Python documentation the term suite is used instead
of block
Example: sign
The following both implement the mathematical sign function:
def sign(x):
if x < 0:
return -1
elif x == 0:
return 0
else: # x > 0
return 1
def sign(x):
if x < 0:
return -1
else:
if x == 0:
return 0
else:
return 1
Boolean operators
nota is True if a is false and False if a is true
aandb is true if a and b are both true and false otherwise
aorb is true if a is true or b is true and false otherwise
Given boolean arguments, the boolean operators behave just as indicated
in the truth table in the week 4 notes
and and or are lazy
and and or are both lazy (also called shortcut or shortcircuit)
operators: their left argument is evaluated first and the right argument is
evaluated only if necessary
if a is true, a or b is true without evaluating b
if a is false, a and b is false without evaluating b
Examples:
x==0or1/x>1000
x!=Noneandx+1<y
Operator precedence revisited
Operator precedence table for all the operators we have seen so far
(highest to lowest precedence):
attribute_reference
function_call
unary + and -, **
*, /, %
binary + and -
==, !=, <, >, <=, >=
not
and
or
Example:
notx==2andx<4orx>6
is the same as
(not(x==2)and(x<4))or(x>6)
Chained ordering operators
Python allows the ordering operators to be chained, as is common in
mathematical usage
Example:
a<=b<c
is equivalent to
a<=bandb<c
Chaining ordering operators is discouraged in this course, since most
computer languages do NOT allow it
instead use and as above (or nested conditional statements, but that
is usually harder to read, and hence not as good style)
the course Python syntax does not include operator chains
How to learn a programming language
Read a text, reference manual, and/or class notes to get the general idea
Study (don't just read) a lot of sample programs
Write a lot of programs (many of them very simple) to exercise your
understanding of specific features
When you get stuck reading or writing programs, review related reference
material
and then don't hesitate to ask for help if you remain stuck!
The idea is to learn most of it by example, but make an effort to
memorize bits that you do not learn thoroughly by example
You are not responsible for memorizing details of functions and
methods in modules (such as math module elements or Reeborg commands)
but be able to use them if provided with reminders of their names
and, if we haven't used them much, further documentation on their use
become familiar with built-in functions introduced in class:
they're built-in because they are frequently used
Contains most of the "facts" you need to know for tests (but you
only develop skill in using these facts through practice)
Links to pages with tools that shows you parse trees
one page allows you to enter your own program
another randomly generates Python expressions
Trees
A tree has
nodes from which one or more branches emanate
branch has a node at one end and a node or a leaf at the other
end
nothing eminates from a leaf
a root from which the rest of the tree is reached
Examples of trees
computer file systems
nodes are directories
leaves are files
a genealogy trees representing descendents of a person
a person is a node if they have offspring, and a leaf otherwise
parse trees
Parse trees
A parse tree represents the syntactic structure of some text that has been
parsed according to a grammar
the name of a syntactic form of the grammar is attached to each node
one or more characters from the text is attached to each leaf
the original text can be reconstructed by scanning the leaves from left
to right (inserting whitespace between leaf text as necessary)
The meaning of a program is determined by its parse tree
The kinds of parse trees that can be constructed determine the kinds of
programs that can be written
Parse tree tools
Please take advantage of two tools linked from the course Python
Syntax page to develop your ability to think in terms of parse trees
The Random syntax generator page has buttons for randomly generating
simple Python expressions or sentences in a tiny fragment of English and
see their corresponding parse trees
The Syntax tree page allows you to type or paste a Python program (in
the syntax we have studied) and see its parse tree