Professional Documents
Culture Documents
Comments
Comments in Python are indicated with a
pound sign, #.
Any text following a # and before the next
carriage return is ignored by the interpreter.
For multiple-line comments a # must be used
at the beginning of each line.
2
Continuation Line
The \ character at the end of a line of Python
code signifies that the next line is a
continuation of the current line.
Data Types
Examples of data types are integers, floatingpoint numbers, complex numbers, strings, etc.
Python uses dynamic typing, which means
that the variable type is determined by its
input.
The same variable name can be used as an integer
at one point, and then if a string is assigned to it,
it then becomes a string or character variable.
6
Long integer
Unlimited except by the machines available memory
11
12
Attributes
Objects may have attributes associated with
them.
The attributes can be thought of as some type of
data that is bound to the object.
Each attribute has a name.
The value of the attribute is found by typing the
name of the object, a period, and then the name
of the attribute, in the form object.attribute
15
16
Methods
A method can be thought of as a function that
belongs to the object, and operates on the objects
attributes, or on other arguments supplied to the
method.
An objects methods are invoked by typing the name
of the object, a period, and then the name of the
method, along with parenthesis for the argument list,
in the form object.method([argument list])
Note: The parenthesis must always be present to invoke a
method, even if there are not arguments needed.
17
18
Strings
The string data type is assigned by enclosing
the text in single, double, or even triple
quotes. The following are all valid ways of
denoting a string literal
Hello there
Hello there
Hello there
Hello there
20
Mixing Quotes
Mixing single, double, and triple quotes allows
quotes to appear within strings.
>>> s = 'Dad said, "Do it now!"'
>>> s
'Dad said, "Do it now!"
>>> print(s)
Dad said, "Do it now!"
21
Triple Quotes
Triple-quoted strings can include multiple
lines, and retain all formatting contained
within the triple quotes.
>>> s = '''This sentence runs
over a
few lines.'''
>>> s
'This sentence runs\n over a\n few lines.'
>>> print(s)
This sentence runs
over a
few lines.
22
Special Characters
Special characters within string literals are preceded
by the backslash, \
One common special character is the newline
command, \n, which forces any subsequent text to
be printed on a new line.
>>> print('Hello \n there.')
Hello
there.
23
24
25
Raw Strings
Raw strings are strings where backslashes are left
as is, and are not interpreted as escape
characters.
Raw strings are defined by preceding the string
literal with r.
>>> s = r'Hello \n there\'.'
>>> print(s)
Hello \n there\'.
26
Formatting Strings
Strings are formatted in Python using the
.format() method.
>>> x = 654.589342982
>>> s = 'The value of x is {0:7.2f}'.format(x)
>>> s
'The value of x is 654.59'
27
Format Specifiers
Spec.
Explanation
Examples
integer
wd
field width of w
45'
+wd
+45'
0wd
'{0:05d}'.format(45) =>'00045'
floating point
w.df
0w.df
+w.df
scientific notation
e
w.de
+w.de
29
Format Specifiers
Spec.
g
Explanation
Examples
w.d%
0w.d%
string
field width of w
s
ws
45.67%'
'
30
Another Example
>>> name = 'Tom Jones'
>>> age = 45
>>> weight = 177.8
>>> height = 70.32
>>> s = 'His name is {0:s}. His is {1:d} years old. He is
{2:.0f} inches tall and weighs {3:.1f} pounds.'
>>> s.format(name, age, height, weight)
'His name is Tom Jones. His is 45 years old. He is 70
inches tall and weighs 177.8 pounds.'
31
list
tuple
32
33
34
Using Ranges
Ranges of indices can also be used. These are
indicated by the form start:end.
IMPORTANT! The last value in the range is NOT
returned.
>>> t
[0, -5, 8, 'hi', False]
>>> t[1:3]
[-5, 8]
>>> t[0:-1]
[0, -5, 8, 'hi']
37
Using Ranges
All the elements from the first up to a given index
(minus one) are accessed by starting with a colon.
All elements from a starting element to the end are
accessed by ending with a colon.
>>> t
[0, -5, 8, 'hi', False]
>>> t[:4]
[0, -5, 8, 'hi']
>>> t[2:]
[8, 'hi', False]
38
Striding
Can specify a stride to skip elements.
A negative stride can move backwards.
>>> t = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> t[0:-1:3]
[1, 4, 7, 10]
>>> t[10:2:-2]
[11, 9, 7, 5]
39
Reversing Elements
A negative stride can move backwards
through list.
To return all the elements of an array in
reverse
order
use
[::-1].
>>> t = [0,-5,8,'hi',False]
>>> t
[0, -5, 8, 'hi', False]
>>> t[::-1]
[False, 'hi', 8, -5, 0]
40
Assigning/Reassigning Elements
Since lists are mutable we can reassign values
to their elements.
>>> p = ['cat', 'dog', 'ferret', 'llama']
>>> p[2] = 'squirrel'
>>> p
['cat', 'dog', 'squirrel', 'llama']
>>> p[0:2] = ['zebra', 'monkey']
>>> p
['zebra', 'monkey', 'squirrel', 'llama']
42
47
Caution!
Notice that the sequence is always one
short of the final number in the
argument.
This is true almost everywhere in Python.
Ranges and sequences of values do not
include the last item in the specified range.
48
Dictionaries
A dictionary is a collection of objects that are
referenced by a key rather than by an index
number.
In other programming languages dictionaries
are referred to as hashes or associated arrays.
50
Dictionaries
Dictionaries are defined using curly braces, with
the key:value pairs separated by a colon.
Elements are accessed by using the key as though
it were an index.
d = {'first':'John', 'last':'Doe', 'age':34}
>>> d['first']
'John'
>>> d['age']
34
51
52
>>> d
{'age': 34, 'last': 'Doe', 'first': 'John'}
>>> d['age'] = 39
>>> d
{'age': 39, 'last': 'Doe', 'first': 'John'}
53
57
58