Python handout - Katie Panciera

advertisement
Python Reference Sheet
CSci1001, Spring 2010
April 6, 2010
This is a quick reference to the basics of the Python
language as we use it in CSci1001. It is by no means
a complete description of Python! However, there is
enough of the language presented here to read and
write interesting and useful Python programs.
Revision: 1.5
which in turn is the same as the Python floatingpoint number 57000.0. Much larger numbers, such
as 6.02e23 are possible (in conventional scientific notation 6.02 × 1023 ), as are small numbers, such as
3.5e-3 (3.5 × 10−3 , or 0.0035) and very very small
numbers such as 6.626e-34 (6.626 × 10−34 ).
Text strings. Python represents strings of text
as sequences of characters enclosed in either single
quotes (’) or double quotes ("). Examples are ‘foo’
Python programs, and programs in general, exist to
and "A string with spaces". You can also inread, manipulate, and display data. Here are three of
clude quote characters in a string, for example, ‘‘A
the fundamental types of data provided by Python.
string with ‘single quote’ characters’’ and
‘A string with ‘‘double quote’’ characters’.
Numbers. We deal with two kinds of Python numbers in CSci1001: integers and floating-point.
Lists. A list in Python is a sequence of values that
Decimal integers are represented by strings of dig- are bound together and can be manipulated as a unit.
its: 42, 0, and 2147483647 are all integers. Do not They are represented in a program by enclosing the
use a leading zero in a decimal integer: a leading zero values in square brackets, [ and ] The values are
is used to introduce modifiers. For example, 0x, as separated by commas. A list of three integers might
describe in the next paragraph.
look like this: [ 32, 7, 19 ]. The values in a list
You can represent an integer in hexadecimal (base- may be of any Python type, for example strings:
16) by preceding it with 0x. Hexadecimal digits are
the decimal digits 0–9 plus the letters a–f. 0x0,
[ ‘apple’, ‘blueberry’, ‘cherry’ ]
0x12a3, and 0xbadfade are all hexadecimal integers.
Floating-point numbers differ from integers in two
ways: they have a fractional part and a wider range.
2 Variables
The fractional part is represented with a decimal
point: for example, these are floating-point numbers:
Variables serve as pronouns in Python: they can
0.0, 3.14159.
stand in for data values, including numbers, strings,
To accommodate their wider range, floating point
and lists.
numbers can be expressed in scientific notation, with
the character e separating the exponent. For example, the Python floating-point number 5.7e4 is Syntax of names. Variable names in Python conthe same as the scientific notation number 5.7 × 104 , sist of a leading character that may be an uppercase
1
Data types
1
Operation
Equality
Inequality
Less than
Greater than
Less-or-equal
alphabetic character, a lowercase alphabetic character, or an underscore; followed by zero or more uppercase alphabetic characters, lowercase characters,
underscores, or digits. The following are valid, distinct variable names: x, X, a1, b_2.
The following are not valid variable names: 3x, a@5
Greater-or-equal
Symbol
==
!=
<
>
<=
>=
Example
4 == 5
4 != 5
4 < 5
4 > 5
4 <= 5
4 >= 5
Value
False
True
True
False
True
False
Assignment and use. The assignment operator,
The main use of these comparisons is in control
=, associates a value with a variable. The left side of structures, described below in Section 8.
the assignment operator is a variable name, and the
The results of comparisons can be combined using
right side is an expression that computes a value to and and or: for example,
assign to the variable. Here are some examples:
4 > 5 or 3 < 5
x = 5
would be True.
y = ‘text string’
Comparisons can be combined with arithmetic exz = 42 + x
pressions and variable references. Here is a more elabsumsq = a * a + b * b
orate example:
disc = b * b - 4 * a * c
v1 * 5 >= v2 ** 3 and v1 < v2
Nota bene: the operator for a test of equality is
two equal signs, ==, and the operator for variable
assignment, described in Section 2 is one equal sign,
Python provides expressions as a means to combine
=. These two operators do very different things!
and manipulate data values. Here are some of the
basic expression types.
Indexing Text strings and lists can be “indexed,”
that is, a program may refer to an individual element.
Arithmetic. Python provides a rich set of arith- Python accomplishes this with the square-brackets
metic operators, shown here. Some of the examples operator, [ ]. For example,
use floating-point numbers, some use integers.
x = [ 6, 7, 8 ]
print x[0], x[2]
Example Value
Operation
Symbol
Add
+
3 + 5
8
will print 6 8, and
Subtract
72 - 21
51
y = ‘abc’
7.2 * 4.5
32.4
Multiply
*
print y[0], y[2]
Divide
/
7 / 3
2
Remainder
%
7 % 3
1
will print a c.
Exponent
**
7 ** 3
343
The leftmost (first) element in a string or list is at
index 0. The rightmost (last) element is at an index
Also, operations can be combined, and grouped
equal to one less than the length; e.g., the string y
with parentheses:
above is 3 characters long, and the index of the last
character is 2, not 3.
7 * ( 4 + 3 ) / 8
Indices past the end of a string or list produce an
error; for instance, given x above, x[3] results in:
Comparison and logic. These operations comIndexError: list index out of range
pare values against one another:
3
Expressions
2
4
Functions
x = [9, 8, 7]
print x
Functions are a way to define and use operations that x.append (0)
aren’t part of the basic set used in expressions above. print x
The Python language provides many built-in functions, and you the programmer may define new ones will print this:
for your own use.
[9, 8, 7]
[9, 8, 7, 0]
Use. A function has a name, defined with the same
rules as variables, using alphabetic characters, dig- Definition. An important part of the power of
its, and the underscore. When using (or “calling”) functions is that you, the programmer, may define
a function, the name of the function is followed by your own. This is done with a def statement. For
a list of “parameters” enclosed in parentheses. The a simple example, here is the definition of a function
parameters are the values to which the function is to return the sum of the squares of two parameters:
applied.
def sumsq (a, b):
For example, if there is a function called sqrt that
a2 = a * a
takes a single argument and computes its square root,
b2 = b * b
it can be called thusly:
return a2 + b2
x = sqrt(4)
y = sqrt(z)
The parts of the definition are:
• The def keyword, which introduces the function
definition.
This will assign the value of the variable x to 2, and
the value of y to whatever the square root is of the
value of variable z.
Function calls may be used as part of expressions,
so:
• The name of the function, in this case sumsq.
• The parameter list, which looks exactly like a series of variables enclosed in parentheses and separated by commas. The parameter names may
be used inside of the function definition just like
variables would be.
hypotenuse = sqrt (a * a + b * b)
ssr = sqrt(x) + sqrt(y)
Python provides built-in functions for common
uses. One of the most important, named len, gets
the length of a list or a string. Thus, the value of
len(‘string’) is 6, because ‘string’ has six characters. The value of len([1, 2, 3]) is 3 because
the list [1, 2, 3] has three elements.
• A colon at the end of the parameter list.
• The function body, which is indented. This is
just a series of Python statements, including assignments and expressions, which are to be executed when the function is called.
• Optionally, the function may contain one or
more return statements: this is the value that
will be the result of the function. For example,
using the definition above,
Methods. There is a special kind of function,
called a “method,” that is associated with values
stored in variables. For example, lists have a method
named append, which adds one item to the end of the
list. Methods are accessed by using the name of the
variable, followed by a period, followed by the name
of the method; this can be used just as any function.
For example:
sumsq (3, 5)
would have a value of 34, the sum of the squares
of the two parameters.
3
Scope. Function parameters and variables defined
in an indented function body are not accessible outside of the function. In programming language parlance, their “scope” is “local” to the function definition. Here is an example:
Output Python provides a statement called print
to display a sequence of values to the terminal. So,
for example,
def fun(a):
b = a * a
return b / 2
x = fun(6)
y = fun(b)
will display 6 to the terminal.
print 4 * 3 / 2
x = 3.7
y = ‘Why not?’
z = [ x, y ]
print x, y, z
The first three lines define a function named fun,
then the following two lines call fun. The first call will display something like this to the terminal:
assigns the value 18 to the variable x. The second 3.7 Why not? [3.7, ‘Why not?’]
call is an error; there is no variable named b to use
as a parameter, because b is defined only within the
body of fun.
6 Libraries
Python provides a library with many, many “modules,” each of which adds some functionality to the
language. For example, there is a math module, which
So far we’ve seen ways to type data into a program provides advanced mathematical functions. Each liwhen we compose the source code. But how can a brary module contains a mix of data and function
running program get data from its environment, e.g., definitions. Here is an example of using the math
the user at the keyboard? How can a running pro- module:
gram report results? This is the province, respecimport math
tively, of “input” and “output.”
p2 = math.pi * math.pi
Input Python provides a built-in function called p2s = math.sqrt(p2)
raw_input to read a line from the keyboard and reThe example shows three important points about liturn it as a string. So this program fragment:
brary modules:
ans = raw_input(‘Enter a number:’)
• To use a module, name it in an import statewill type this on the display:
ment.
Enter a number:
• To use a value defined in a module, Python needs
and the program will then wait for the user to type
to know the module that defines the value and
a line. If the user types 67 (followed by Enter), then
the name of the value, separated by a period.
ans will have as its value the text string ‘67’.
In this case, the math module provides a value
Remember that a text string is not an integer. For
named pi. The second line of the example asthe rest of the program to use the result of raw_input
signs the square of π to the variable named p2.
as an integer, it must be converted. Conversion of
• Similarly, to use a function defined in a moda string containing only digits can be accomplished
ule, tell Python the name of the module and the
with the Python built-in int:
name of the function. The third line of the exval = int(ans)
ample uses the math square root function, named
sqrt,
to compute the square root of p2.
now val will contain the integer 67.
5
Input/Output
4
7
More About Lists
of the program to vary according to the data the program is processing. This is called “control structure,”
and in Python it is facilitated by a number of language constructs.
Here is more information about lists. The following
initializes a list of of 31 zero entries, asks the user to
input numbers, counts how many times certain numbers occur, and prints out the count in two different Sequences. The most basic control structure is to
ways. Notice the use of the following constructs:
do one thing after another. This is represented in
Python by the order of statements in the program
• Initializing a long list using range.
text.
• Accessing a list element using [ and ].
import math
• Using a sublist: hist[a:b] is the sublist of items a = 2 + 3
b = math.sqrt(a)
hist[a], hist[a+1], . . ., hist[b-1].
• Getting a list length using len.
If and Else. To make a decision based on data
values, use if, as in this example:
• Stepping through a list using range and len.
if a > b:
print a - b
if a > 0 and b > 0:
print a / b
# Set up a list of 31 zeros.
hist = [0 for i in range(0, 31)]
# Count number of times each valid
# input value occurs.
p = int(raw_input("Enter a number"+ \
"between 0 and 30 (-1 to exit): "))
while (p != -1):
if (p >= 0 and p <= 30):
# Add 1 to the count for p
hist[p] = hist[p] + 1;
p = int(raw_input("Enter a number"+ \
"between 0 and 30 (-1 to exit): "))
The if statement takes a comparison expression, as
defined above in Section 3, followed by a colon, followed by indented statements to execute if the comparison expression is True.
A variation on the theme is the either-or construct:
if a > b:
print a - b
else:
print b - a
# Printout 1: counts, 10 per row.
print hist[0:10]
print hist[10:20]
print hist[20:30]
print hist[30:31]
Depending on the relative values of a and b, this
Python fragment will choose one or the other of the
print statements.
While. This is a looping construct: it executes a
sequence of statements repeatedly, as long as a condition is satisfied.
# Printout 2: 1 per row along with index i
for i in range(0, len(hist)):
print i, hist[i]
8
i = 0
x = 0
while
x =
i =
print
Control structures
As we have seen in pseudocode, one of the basic necessities of programming is for the execution of parts
5
i < 10:
x + i
i + 1
i, x
This snippet will execute the two lines of indented 9
Miscellaneous
code until the value of the variable i reaches 10. The
Comments are used in programming to add notes for
result printed will be 10 45.
humans to read. They are not part of the program
itself, and do not alter the behavior of the program;
For. The for statement provides a way to iterate Python ignores them.
over values, such as lists and strings, that are conA comment in Python is everything in a line after
structed from multiple parts. A simple example will a pound-sign character, #.
clarify:
Also, for readability, sometimes it is convenient to
break long lines before they are done. This is done
for a in [ 1, 2, 3 ]:
with the backslash character \. The following two
print a, a*a
examples are equivalent:
The indented body of the statement is executed re- print ‘This line’, 5, ‘looks’, 7, ‘random.’
peatedly. Each time, the variable a takes on the value
of one of the elements of the list [1, 2, 3], in se- and
quence. The output of this loop will be
print ‘This line’, \
5, ‘looks’, \
1 1
7, ‘random.’
2 4
3 9
Python ignores the backslash-newlines and combines the lines before figuring out how to execute
The built-in function range produces a list of num- them. Both of the above print:
bers suitable for use with for. For example, the
This line 5 looks 7 random.
above loop could have been accomplished this way:
for a in range(1, 4):
print a, a*a
10
Example
Here is a complete example, illustrating many of the
Note that range(a, b) produces a list of consecconstructs described above.
utive integers that start with a and end with b-1.
This is ideally suited for indexing Python strings and def gcd(a, b):
arrays, so:
# The GCD of anything and 0 is 0
if a == 0:
x = ‘Alas, a string!’
return b
for i in range(0, len(x)):
print x[i]
# Compute the GCD of a and b
while b != 0:
if a > b:
a = a - b
else:
b = b - a
return a
will print
A
l
a
s
,
print gcd(7, 21)
and so forth.
6
Download