Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

CSC220 Data Structures Fall 2014

Python II
Last time we covered the very basics of Python, leveraging knowledge you already know about programming in general –
variables, conditionals, loops, functions, etc. Now we'll continue our Python introduction and start using more Python
specific concepts.

Dictionaries
One more built-in type that is incredibly useful is the dictionary known in Python as the dict. I think of them as arrays
where the index is a string instead of an integer. These indices are keys and a dict is made up of key, value pairs.

>>> # create with literal dictionary, use braces


>>> states = {'IL' : 'Illinois', 'IN' : 'Indiana', 'IO' : 'Iowa'}
>>> # empty dict
>>> teams = {}

>>> # using the constructor on a list of string tuples


>>> lights = [('red', 'stop'), ('yellow', 'caution'), ('green', 'go')]
>>> stoplight = dict(lights)
>>> stoplight
{'red' : 'stop', 'yellow' : 'caution', 'green' : 'go'}
>>> # to access a value use dict['key']
>>> stoplight['red']

More on functions
Just like most languages with which you might already be familiar, Python functions create a local scope. Variables created
inside of function are not visible outside of it.

def line(m,x,b):
y = m * x + b
return y

ordinate = line(5, 3, 7)
print(ordinate)

# ERROR, m not visible outside of function


print(m)

Variable names will resolve to the innermost definition.

# define m outside of line


m = 7
# line's m is a completely separate variable, so this will
# return the expected.
ordinate = line(1, 1, 1)

For lists, Python passes by reference instead of by value. That means you can alter a mutable sequence "in place."

run = [1, 2, 3, 4, 5, 6, 7]
def double_in_place(l):
# len(run) returns 7
# range(len(run)) returns 0,1,2,3,4,5,6
for i in range(len(l)):
l[i] *= 2
# as opposed to making a copy
def double_copy(l):
output = []
for val in l:
output += [val*2]
return output

Similarly to other languages, by default parameters are positional, that is, order matters.
# this
line(5, 3, 2)

# is different than
line(2, 3, 5)
Keyword arguments are when you give the parameter values by name. In that case, order doesn't matter.

# this
line(m = 5, x = 3, b = 2)

# is the same as
line(x = 3, b = 2, m = 5)
Notice you don't have to change anything about the function definition for this to work. However, you can use a
similar syntax to set default values for a function.

def line(m = 1, x = 1, b = 1):


return m * x + b

The last thing about Python functions that is really interesting is you can simulate returning multiple values.

def square_and_cube(x):
return x**2, x**3

square, cube = square_and_cube(24.5)


You're still actually returning only one thing, a tuple, it just happens to look like two things because in this case the
parentheses are optional. Returning multiple values as a tuple is known as packing while assigning them is known as
unpacking. This can be incredibly useful. In C, you often have to either change a function to create a structure to do
something like this.

List Comprehensions
Another common Python-ism you might run into is list comprehensions. You can use these to generate a list on the fly if
you need it.

# boring way
squares = [1, 4, 9, 16, 25, 36, 49]

# with a comprehension
squares = [x**2 for x in range(1,8)] # range(start,stop)
You can also add logic to a comprehension to make lists exactly the way you want them.

# squares of multiples of three


mylist = [x**2 for x in range(100) if x % 3 == 0]
# quad combinations of adenine, thymine, guanine and cytosine
[x + y + z + w for x in 'ATGC'
for y in 'ATGC'
for z in 'ATGC'
for w in 'ATGC']

It's considered 'Pythonic' to use list comprehensions in many places where in other languages you'd write short loops, so
you'll see them often.
Modules
Instead of header files and linking to libraries, Python imports modules.

# to get trig functions


import math

# access with dot operator


y = math.sin(3.14159/2.0)

# to avoid having to type 'math.' all the time, ~ to 'using' in C++


from math import *

# or if only using a particular function(s)


from math import cos, sin, tan

We'll be writing our own modules as we go on. By default, when a module is imported, it will evaluate all the statements.
That's fine if it only contains function definitions, but if there's other code, say testing code or example code, having that
execute on importation is probably not what you want. We get around this by checking what name the interpreter thinks the
module has when it's imported.

# Top of the module file is a bunch of function definitions


def square(x):
# ...

def normalize(x):
# ...

# check when loading, those are double-underscores.


# if this file is run directly from the command line
# then Python thinks its name is '__main__' and will evaluate
# the if body.
if __name__ == '__main__':
# test/example code can go here
print('square of 100', square(100))
# ...

# However, if it's imported in another script, then it's name


# isn't __main__ and only the defs will be loaded into memory.

This is very common. Use this for everything where in C or C++ you'd normally write a header and separate source file.

Be sure to check the Python documentation for what modules are availble besides math and what their contents are.
Taking user input

n = int( input('please enter an integer number') )


m = float( input('please enter a float number') )

Output and tuples


The most common way to output text in Python is with print. If you need to mix text with other data, then you can use the
comma operator to create a tuple on the fly to send to the print statement:

colors = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow']


print('The list of colors', colors, 'consists of primary and secondary colors.')
There are ways to do precise formatting, e.g., if you want to have numerical data to exactly 3 decimal places so everything
lines up nicely, but this use of print should be sufficient to start.

Lists of mixed types


Python lists are very versatile. You can arbitrarily mix types within a list. You can think of lists as a type of C struct, but with
index element access instead of member access:

# type, cost per lb, lbs


fruit = ['bananas', 2.99, 0.5, 'apples', 3.99, 1.0]

# parabola points as a list of tuples


coords = [(0.0, 0.0), (1.1, 1.1), (2.0, 4.0), (3.0, 9.0)]
print(coords[2][1] )
coords[2][1] = 9.0 # error

# parabola points as a list of lists


points = [ [0.0, 0.0], [1.1, 1.1], [2.0, 4.0], [3.0, 9.0] ]
points[2][1] = 9.0
print(points)

converted by W eb2PDFConvert.com

You might also like