Every variable in Python is actually an object. You don’t have to write object-oriented (OO) code to use Python, but the way Python is constructed encourages an OO approach.1
Object Types
All variables have a type that can be seen by using the built-in type() function.
>>> type(23)
<type 'int'>
>>> type('some more text')
<type 'str'>
>>> c=[1,2,'some more text']
>>> type(c)
<type 'list'>
Other types are 'class', 'module', 'function', 'file', 'bool', 'NoneType', and 'long'.
The special constants True and False are 'bool' types. The special constant None is a 'NoneType'.
To see a textual definition of any object, you can use the str() function; for example, the variable c can be represented as a string:
>>> str(c)
"[1,2,'some text']"
Factory Functions
There are a series of functions that create variable types directly. Here are the most commonly used ones.
int(4.0)
| Creates integer 4 |
str(4)
| Creates string '4' |
list(1, 2, 3, 4)
| Creates list [1,2,3,4] |
tuple(1, 2, 3, 4)
| Creates tuple (1,2,3,4) |
dict(one=1, two=2)
| Creates dictionary {'one':1,'two':2} |
Numbers
Integer numbers
have no realistic limit; you can store and manipulate numbers with 1,000 digits, for example. These are stored as “long” numbers, for example:
>>> 12345678901234567890
12345678901234567890
Real numbers
(i.e., those with decimal points) are stored with what is called double-precision. For example:
>>>1 / 7.0
0.14285714285714285
The actual degree of precision depends on the architecture of the hardware you use.
Very large or very small real numbers can be described using scientific notation.
>>> x = 1E20
>>> x / 7.0
1.4285714285714285e+19
>>> int(x/7.0)
14285714285714285714286592
>>> y = 1E-20
>>> y / 7.0
1.4285714285714285e-21
Arithmetic Operators
The four arithmetic operators
work as expected.
# Addition
2 + 3
2.0 + 3
# Subtraction
3 - 2
3.0 - 2
# Multiplication
3 * 2
3 * 2.0
3.0 * 2.0
# Division
3 / 2
-6 / 2
-6 / 4
3 / 2.0
|
# Integer 5
# Real 5.0 (if one or more operands
# are real)
# Integer 1
# Real 1.0
# Integer 6
# Real 6.0
# Real 6.0
All divisions produce real numbers
# 1.5
# -3.0
# -1.5
# 1.3
|
Other Operators
# Modulus
15 % 4
# Exponentiation
4 ** 3
-4 ** 3
4 ** -3
|
# Real 3.0 (remainder after
# dividing 15 by 4)
# Integer 64
# Integer -64 (the '–' applies to
# the result)
# Real 0.015625 (NB negative
# exponents force operand to real
# numbers
|
Conversion Functions
int(1.234)
int(-1.234)
long(1.234)
long(-1.234)
long('1234')
long('1.234')
long(float('1.234'))
float(4)
float('4.321')
|
# Integer 1
# Integer -1
# Long
1L
# Long -1L
# Long 1234L
# ** error ** needs 2
#
conversions
# Long 1L (after two
# conversions)
# Real 4.0
# Real 4.321
|
Boolean Numbers
Booleans
are actually held as integers but have a value of either True or False.
bool(23)
bool(0)
bool('any text')
bool('')
bool([])
|
# True - all nonzero integers # False -
zero
# True – any string
# False – zero length strings
# False – empty lists
|
Random Numbers
Two random number
generators are useful (you need to import the random module).
import random
random.randint(a,b)
random.random()
|
# Generates a random integer
# between a and b inclusive.
# Generates a random real
# number between 0.0 and 1.0
|
Sequences: Strings, Lists, and Tuples
So far, we have looked at variables that hold a single value. A sequence is a variable that holds multiple values as an array. Each element can be addressed by its position in the sequence as an offset from the first element. The three types of sequence are as follows:
- Strings : A sequence of characters that together form a text string.
- Lists : A sequence of values where each value can be accessed using an offset from the first entry in the list.
- Tuples : A sequence of values, very much like a list, but the entries in a tuple are immutable; they cannot be changed.
We’ll look at the Python features that are common to all sequences and then look at the three types separately.
Sequence Storage and Access
The elements of a sequence are stored as a contiguous series of memory locations. The first element in the sequence can be accessed at position 0 and the last element at position n – 1 where n is the number of elements in the sequence (see Figure 2-1).
Figure 2-1.
Storage of elements of a sequence
You can iterate through the elements of a sequence x having n elements starting at element x[0] and adding +1 each time x[1], x[2] ¼ x[n-1], and so on. You can also iterate from the end and subtract 1 each time: x[n-1], x[n-2] ¼ x[0].
Membership
A common check is to determine whether a value exists in a sequence. For example:
'a' in 'track'
9 in [1,2,3,4,5,6]
|
# True
# False
|
'x' not in 'next'
'red' not in ['tan','pink']
|
# False
# True
|
Concatenation2
Two or more sequences can be added together to make longer sequences. The plus sign (+) is used to concatenate strings, lists, or tuples.
sequence1 + sequence2
|
# results in a new sequence
# that appends sequence2 to
# sequence1
|
'mr'+'joe'+'soap'
|
# 'mrjoesoap'
|
Sequence Elements and Slices
A sequence is an ordered list of elements, so a single element is identified by its offset from the first. A slice is a convenient way to select a subset of these elements in sequence, producing a new sequence. A slice
is identified using this notation:
[startindex:endindex]
The slice will consist of elements starting as the startindex up to but not including endindex.
Some examples will make it easier to understand:
mylist=['a','b','c','d','e']
mylist[0]
mylist[3]
mylist[5]
mylist[-1]
mylist[1:3]
mylist[:4]
mylist[3:]
|
# a list with five
# elements
# 'a'
# 'd'
# results in an error
# 'e'
# ['b','c']
# ['a','b','c']
# ['d','e']
|
Sequences can be nested and elements accessed using multiple indexes, for example:
mylist = [1,2,3,['a','b','c'],5]
mylist[2] # 3
mylist[3] # ['a','b','c']
mylist[3][1] # 'b'
Sequence Built-In Functions
mylist=[4,5,6,7,1,2,3]
len(seq)
len(mylist)
max(seq)
max(mylist)
min(mylist)
|
# the length of seq
# 7
# maximum value in
seq
# 7
# 1 – the minimum
|
Strings
A
string
is a sequence of characters that make up a piece of text. Strings are immutable, but you can update the value of a string by assigning a new string to the same string variable.
>>> mystr = 'Paddington Station'
>>> mystr=mystr.upper() # replaces mystr
>>> mystr
PADDINGTON STATION
Assignment
You can delimit strings with either single (') or double (") quotes, as long as they are matched. You can embed either quote inside the other.
>>> text = 'Hello World!'
>>> longtext = "A longer piece of text"
>>> print(text)
Hello World!
>>>longtext
'A longer piece of text'
>>> text = 'Paul said, "Hello World!"'
>>>print(text)
Paul said, "Hello World!"
Accessing Substring s
You access substrings with slices, of course:
text='Paul said, "Hi"'
text[:4]
text[-4:]
text[5:9]
text[0:4] + text[12:14]
|
# 'Paul'
# '"Hi"'
# 'said'
# 'PaulHi'
|
String Comparison
Strings can be compared3 as follows:
'mcr'>'liv'
'liv'>'tot'
'mcr'=='X'
'X'>'t'
|
# True
# False
# False
# False
|
Membership (Searching)
We can check whether a substring is in a string, character by character or using substrings. The outcome is a Boolean.
'a' in 'the task'
'w' in 'the task'
'as' in 'the task'
'job' not in 'the task'
'task' in 'the task'
|
# True
# False
# True
# True
# True
|
Special Characters and Escaping
A string can contain nonprinting and control characters (e.g., tab, newline, and other special characters) by “escaping
” them with a backslash (). Common escape characters are the following: