Skip to content
Register Sign in Wishlist

Code for chapter 18


Below are listed all the scripts as shown in chapter 18 of the book. These are free to copy and paste into your code editor.

Quick links to each script:

18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 18.10
18.11 18.12 18.13 18.14 18.15 18.16 18.17 18.18 18.19 18.20
18.21 18.22 18.23 18.24 18.25 18.26 18.27 18.28 18.29 18.30
18.31 18.32 18.33 18.34 18.35 18.36 18.37 18.38 18.39 18.40
18.41 18.42 18.43 18.44 18.45 18.46 18.47 18.48 18.49 18.50
18.51 18.52 18.53 18.54 18.55 18.56 18.57 18.58 18.59 18.60
18.61 18.62 18.63 18.64 18.65          

Script 18.1

script_18_1.py
# Script 18.1
mass = 3.4
volume = 1.8
density = mass/volume       # Division
density = round(density, 3) # Round to three decimal places
print(density)
script_18_1.out
[ah@hobbes Documents]$ python script_18_1.py 
1.889
[ah@hobbes Documents]$


Script 18.2

script_18_2.py
# Script 18.2
x = 2     # Integer
y = 5     # Integer
z = 3.0   # Floating point

print(x * y) # 10  - Integer
print(x / y) # 0.4 - Floating point due to division
print(x + z) # 5.0 - Floating point

t = type(x * y - z)  # Get a value's data type
print(t)             # float
script_18_2.out
[ah@hobbes Documents]$ python script_18_2.py 
10
0
5.0
<type 'float'>
[ah@hobbes Documents]$

 

Script 18.3

script_18_3.py
# Script 18.3
x = 1            # An arbitrary integer
print(x.__doc__) # Print Python documentation for this object
script_18_3.out
[ah@hobbes Documents]$ python script_18_3.py 
int(x=0) -> int or long
int(x, base=10) -> int or long

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.

If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base.  The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
[ah@hobbes Documents]$

 

Script 18.4

script_18_4.py
# Script 18.4
x = True
print(x)
print(bool(0.0)) # False
print(bool(7))   # True
script_18_4.out
[ah@hobbes Documents]$ python script_18_4.py 
True
False
True
[ah@hobbes Documents]$

 

Script 18.5

script_18_5.py
# Script 18.5
x = 2
print(x > 5) # False
y = x < 3
print(y)     # True
script_18_5.out
[ah@hobbes Documents]$ python script_18_5.py 
False
True
[ah@hobbes Documents]$

 

Script 18.6

script_18_6.py
# Script 18.6
x = 1
y = -1
x > y and y > 1   # False - second comparison is False
print(x > y and y > 1)
x != 2 or y == 1  # True - first comparison is True; x does not equal 2
print(x != 2 or y == 1)
not (y > x)       # True - comparison is False; not False is True
print(not (y > x))
script_18_6.out
[ah@hobbes Documents]$ python script_18_6.py 
False
True
True
[ah@hobbes Documents]$

 

Script 18.7

script_18_7.py
# Script 18.7
x = 'Hello'
y = "world"
print(x,y)  # Print both values to screen
script_18_7.out
[ah@hobbes Documents]$ python script_18_7.py 
('Hello', 'world')
[ah@hobbes Documents]$

 

Script 18.8

script_18_8.py
# Script 18.8
x = '''This text flows from one line
to the next line inside triple quotes'''
print(x)
script_18_8.out
[ah@hobbes Documents]$ python script_18_8.py 
This text flows from one line
to the next line inside triple quotes
[ah@hobbes Documents]$

 

Script 18.9

script_18_9.py
# Script 18.9
x = 'abcde'
print(len(x)) # 5
print(x[0])   # First character 'a' at index 0
print(x[-1])  # Last character 'e'
print(x[1:3]) # 'bcd' range from index 1, up to, but not including 3
script_18_9.out
[ah@hobbes Documents]$ python script_18_9.py 
5
a
e
bc
[ah@hobbes Documents]$

 

Script 18.10

script_18_10.py
# Script 18.10
name = 'Mary'
x = 0.12
y = 34121.0

a = 'Hello {}'.format(name)    # name replaces brackets
print(a)                       # 'Hello Mary'

b = 'X {:.5f} Y {:.2e}'.format(x, y)   # 5 dp float 2 dp sci
print(b)                               # 'X 0.12000 Y 3.41e4'
 
c = '{:3d},{:3d}'.format(12,7)   # pad digits to 3 characters
print(c)                         # ' 12,  7'
script_18_10.out
[ah@hobbes Documents]$ python script_18_10.py 
Hello Mary
X 0.12000 Y 3.41e+04
 12,  7
[ah@hobbes Documents]$

 

Script 18.11

script_18_11.py
# Script 18.11
x = ['a', 'b', 'c', 'd']
print(x[2])   # 'c' - the character at index 2
print(x[1:])  # ['b', 'c', 'd'] - from index 1 to the end
x[0] = 'z'    # character at index 0 is set to 'z'
del x[2]      # Deletes item at index 2
print(x)      # ['z', 'b', 'd']

y = [[4,7], [9,6]] # A list containing two other lists
print(y[1])        # [9,6] - the sub-list at y index 1
print(y[1][0])     # 9 - item 0 from sub-list 1  
script_18_11.out
[ah@hobbes Documents]$ python script_18_11.py 
c
['b', 'c', 'd']
['z', 'b', 'd']
[9, 6]
9
[ah@hobbes Documents]$

 

Script 18.12

script_18_12.py
# Script 18.12
x = list('PQRST')     # Create list from text string
print(x)              # ['P','Q','R','S','T'] - list of characters
y = list(range(10))   # A list of the range from 0 up to <10
print(y)              # [0,1,2,3,4,5,6,7,8,9]
script_18_12.out
[ah@hobbes Documents]$ python script_18_12.py 
['P', 'Q', 'R', 'S', 'T']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[ah@hobbes Documents]$

 

Script 18.13

script_18_13.py
# Script 18.13
x = [4, 1, 0] # Three items
a, b, c = x   # a is 4, b is 1, c is 0
x = ['a', 'b', 'c', 'd']
print(len(x))     # 4 - number of items in list
print('c' in x)   # True - string 'c' is in the list
print(2 in x)     # False - number 2 is not in list
script_18_13.out
[ah@hobbes Documents]$ python script_18_13.py 
4
True
False
[ah@hobbes Documents]$

 

Script 18.14

script_18_14.py
# Script 18.14
x = (9, 3, 1, 0)  # Create a tuple
y = (2,)          # Tuple with one item (needs trailing comma)
z = ()            # Empty tuple

print(x[-1])      # Print the last item - 0
#x[0] = 6          # Does not work! Tuples cannot be changed!

w = list(x)       # Create equivalent list from a tuple
w[0] = 6          # List copy can be changed
print('x',x)
print('w',w)
script_18_14.out
[ah@hobbes Documents]$ python script_18_14.py 
0
('x', (9, 3, 1, 0))
('w', [6, 3, 1, 0])
[ah@hobbes Documents]$

 

Script 18.15

script_18_15.py
# Script 18.15
x = {1,2,3,4,3,2,1}  # x is {1,2,3,4} - duplicates ignored
y = set([3,4,5,6])   # y created from a list
print(len(y))        # 4
print(1 in y)        # False; 1 is not in y
print(x & y)         # {3,4} - intersection, items in both
print(x | y)         # {1,2,3,4,5,6} - union, items in either
script_18_15.out
[ah@hobbes Documents]$ python script_18_15.py 
4
False
set([3, 4])
set([1, 2, 3, 4, 5, 6])
[ah@hobbes Documents]$

 

Script 18.16

script_18_16.py
# Script 18.16
d = {"G":329.21, "C":289.18, "A":313.21, "T":314.19}
print(d['A'])      # 313.21 -  value associated with 'A'
print(len(d))      # 4 - number of key:value pairs
print(d.keys())    # Just keys 'G', 'A', 'T', 'C'
print(d.values())  # Just values 329.21, 313.21, 314.19, 289.18
script_18_16.out
[ah@hobbes Documents]$ python script_18_16.py 
313.21
4
['A', 'C', 'T', 'G']
[313.21, 289.18, 314.19, 329.21]
[ah@hobbes Documents]$

 

Script 18.17

script_18_17.py
# Script 18.17
d = {"G":329.21, "C":289.18, "A":313.21, "T":314.19}
d['T'] = 304.19   # Change the value of an existing item
d['U'] = 291.08   # Add a new key:value pair
print(len(d))     # 5 - dict is larger  
del d['U']        # Delete a key and its value from the dictionary
script_18_17.out
[ah@hobbes Documents]$ python script_18_17.py 
5
[ah@hobbes Documents]$

 

Script 18.18

script_18_18.py
# Script 18.18
x = ['Mon', 'Tue', 'Wed'] # A list of strings
y = ['Fri', 'Sat', 'Sun'] # And another
x.append('Thu')  # Add a single new item to end
print(x)
x.extend(y)       # Extend with items from another collection
print(x)
x.sort()         # Sort contents alphabetically
print(x)
x.remove('Sun')  # Remove an item
print(x)
x.index('Sat')   # Positional index of an item
print(x)
script_18_18.out
[ah@hobbes Documents]$ python script_18_18.py 
['Mon', 'Tue', 'Wed', 'Thu']
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
['Fri', 'Mon', 'Sat', 'Sun', 'Thu', 'Tue', 'Wed']
['Fri', 'Mon', 'Sat', 'Thu', 'Tue', 'Wed']
['Fri', 'Mon', 'Sat', 'Thu', 'Tue', 'Wed']
[ah@hobbes Documents]$

 

Script 18.19

script_18_19.py
# Script 18.19
s = {'G', 'C', 'A', 'T'}   # A set with 4 strings
t = {'N', 'R', 'Y'}
print(s)
s.add('U')       # Add a single item (if not present)
print(s)
s.update(t)      # Add any new items from another collection
print(s)
script_18_19.out
[ah@hobbes Documents]$ python script_18_19.py 
set(['A', 'C', 'T', 'G'])
set(['A', 'C', 'U', 'T', 'G'])
set(['A', 'C', 'G', 'N', 'R', 'U', 'T', 'Y'])
[ah@hobbes Documents]$

 

Script 18.20

 

Sign In

Please sign in to access your account

Cancel

Not already registered? Create an account now. ×

Find content that relates to you

Join us online

This site uses cookies to improve your experience. Read more Close

Are you sure you want to delete your account?

This cannot be undone.

Cancel

Thank you for your feedback which will help us improve our service.

If you requested a response, we will make sure to get back to you shortly.

×
Please fill in the required fields in your feedback submission.
×
script_18_20.py