Вы находитесь на странице: 1из 20

python lab

Coding the Matrix, Summer 2013


Hi, Please fill out the stencil file named python lab.py. While we encourage you to complete the Ungraded
Problems, they do not require any entry into your stencil file.

Python http://xkcd.com/353/

http://xkcd.com/353/
We will be writing all our code in Python
Python (Version
3.2). In writing Python code, we emphasize the use
of comprehensions, which allow one to express computations over the elements of a set, list, or dictionary
without a traditional for-loop. Use of comprehensions leads to more compact and more readable code, code
that more clearly expresses the mathematical idea behind the computation being expressed. Comprehensions
might be new to even some readers who are familiar with Python, and we encourage those readers to at least
skim the material on this topic.
To start Python, simply open a console (also called a shell or a terminal or, under Windows, a Command
Prompt or MSDOS Prompt), and type python3 to the console/shell/terminal and hit Enter. After a few

Introduction

This document is split into two sections.The first section I have included details on how to install
python and also which version to use. In the second section Ive tried to include notes on whatever I
have covered in class along with few solved problems and a few more for you to try out yourself.
I have tried to make the notes such that anyone with/without any prior computer programming
experience and have been unfortunate enough to miss the first few classes of the python course
can have a good idea about PYTHON.

Section I
Choosing a Version
There are two versions of Python that are currently under development: 2.x and 3.x.
There are features that are constantly being added with each version of python. Some features
have brought some radical changes to the language. Therefore, learning one version but using an
older version can be bit annoying and could lead to excessive hair loss, violent behaviour and
shattered computer screens. So its highly recommended to stick with one version and look out for
consecutive iterations of python and update yourself.

On a lighter note, most of the time developers(Really nice people!) tend to add features to both
versions of python, so next time you see any developer do gift them chocolates (They tend to like
it).
However, the notes correspond to Python version 3.4.2. So not much of a choice here unless you'd
want to take the pain of using an older version.Good luck with that!

Installing

Python Shell:
Lets you run commands line by line
Text Editor:
When you have typed your code in a text editor and have given it a .py extension.This code can be
run later from your terminal or any python IDE.

Installing the Interpreter

Once you have downloaded the version of python for your OS, run the installer and then python is
set up for your computer.

Additionally you'd get a python IDLE GUI application installed. There are other IDEs and editors
but we will use IDLE or terminal for now.

Note to Mac OS X users:


There is a version of python (2.7.6) pre-installed shipping with every mac which can be used by
simply typing the command python in the terminal, but I recommend installing the latest version
from python.org because screwing up with the built-in versions might lead to issues with future OS
X updates as Apple uses the built-in version of python for system updates.

Running Python
To run a python script that is typed in a file with a .py extension, simply type
>>>python path to the file.py
This works in terminal(OS X, linux) and also Command Prompt(Windows)
example:
>>> python Users/Desktop/hello.py

Or
You can open IDLE and type your code and run it right in the shell
Or
You can open files with .py extension in IDLE and press F5 which runs the script.

Section II
Note: I would recommend trying out the commands that follow yourself if you are to read beyond
the line below!

Ive made the code snippets in italic.

Hello World!
Open up IDLE Shell and type
Python 3.x
>>>print (Hello World!)
Hello World!

Python 2.x
>>>print Hello World!
Hello World!

It is that simple!
You'd notice that the syntax is different for version 2.x and 3.x.
Thats because print is a function in 3.x and a statement in 2.x.
More on that later.As for now think that functions have brackets and statements dont.
Well lets make it simpler.
>>>Hello World!
Hello World!

Yes, Python is that simple!

Moving On..
Note:Single line Comments in python are written after #

Task1: Print in your name or what ever stuff you could think of!

Lets print more!

>>>Print (Hello World! *3)


Hello World!Hello World!Hello World!
well that didn't look clean!
>>>Print (Hello World!\n *3)
Hello World!
Hello World!
Hello World!

Quick Note: For all those who got errors for the above code,
Wake up!
Stop copying and pasting the code blindly!
The there is no Print in python
there is only print and yes python is case sensitive language!
\n -adds a a new line

Task2: Try to print such that your output is - He said Everything is awesome!

You can use either or to encapsulate your string. The python interpreter checks for the first
instance of or and the last instance of or respectively and whatever goes in between is
considered as a string. Additionally you can use a \ before or in your text.
>>>Its awesome
Its awesome
>>>It\s awesome
Its awesome

Variables
Variables are named entities which act as containers of data. Any kind of data can be contained in
a variable.

Variable name = value to be stored in that variable.


>>>x = 12
>>>x
12
>>>name=name
>>>name
name
>>>a=1+1
>>>a
2

REPL
Python is what we call a REPL type language.
REPL- Read Evaluate Print Loop
Python first reads the code, evaluates the code, prints the output(not necessarily to the console)
and loops if there is any requirement to do so.
For instance:
>>>print (25*32)
800
>>>pi=22/7
>>>pi
3.142857142857143
>>>print(pi+pi)
6.285714285714286
>>>print(Hello World!*3)
Hello World!Hello World!Hello World!

Task:Take variables sqr and give it any real number value.Print the square of the

Data Types
Numbers
Numbers can be either integers or floating point numbers.
Integers are whole numbers Floats have a decimal point.

Strings
String are lines of text that can contain any characters. They can be declared with single or
double quotes. Whenever you see an output in python which is enclosed in quotes, it
simply means python thinks its a string.Be careful because operators have different
operations for strings and numbers.
>>>empty = ""
>>>escaped = "Can\'t"
>>>greeting = "Hello World"
>>>multiLine = "This is a long \n\ string of text"
You have to escape single and double quotes within the string with a backslash. Otherwise, Python
will assume that youre using them to end the string. Insert line breaks with \n. Python also
supports string interpolation using the percent symbol which is deprecated and you should either
use .format().
>>>name = "John Doe"
>>>greeting = "My name is {}".format(name)

You can access sets of characters in strings with slices, which use the square bracket
notation:
>>>print("Hello"[2])
l
>>>Hello + + World
Hello World

Booleans
Booleans represent either a True or False value. Its important to note that you have to
make the first letter capital. They represent data that can only be one thing or the other.

>>> t= True
>>>t
True
>>>f=False
>>>f
False

Operators
Operator

symbol

example

Addition

>>>2+3
5

Subtraction

>>>3-2
1

Multiplication

>>>4*4
16

Division

>>>6/2
3

Exponentiation

**

>>>3**2
9

Integer Division

//

>>>5//2
2

Modulo

>>>5%2
1

Membership testing

in/ not in

>>>e in hello
True
>>> e not in hello
False

Or

or

>>> 0 or 1
0
>>>1 or 2
1

And

and

>>>0 and 1
0
>>>1 and 1
1

Not

not

>>> e not in hello


False

Equality testing

==

!=

>>> 1==2
False
>>>1!=2
True

Comparison

>,<,<=,>=

>>> 1>=2
False
>>> 1<2
True

Assignment Operators

= , += , -= , /=, *= , %=, //= ,**=


(Note: These operators assigns
the value of the right operand to
the left, if there is any additional
operator before = then that gets
evaluated first then its followed by
the = operator, for instance a+=2
is simply a=a+2

>>>a=2
>>>a
2
>>>a+=2
>>>a
4
>>>a**=2
>>>a
16

Conditional Expressions
Conditional statements are those which are executed only when a particular boolean expression is
evaluated.
The basic syntax of conditional expressions:

expression if condition else expression


example:
>>>x=4
>>>y=0
>>> x*y if y==0 else x/y
0

Here we see that the conditional performs x*y because y==0 is true, had y been something other
than 0, the output would have been x/y
Task:
Assign any random value to x and y as 0.
Think what the output would be for the following expression:
x/y**y if y+1>0 else y/y
Check your answer by executing the code.
The above task would give you a brief idea about the order of precedence of operators in python.
Hint: PEDMAS

Type Casting
Some times we might want to change the type of a specific data type. For instance when we have
x=2 and we try to execute 2*x we would get 22 as the output. This is because here we see that
2 is of type string and the multiplication operation simply gives 2 strings concatenated.Here we
will have to change the type to int or float to make mathematical operations.The syntax for this is
type(data of different compatible type).
Also make sure that the data inside the parenthesis should be of compatible nature.
>>>int(2)
2
>>>str(2)

2
>>>int(2.4)
2
However you'll get an error if you try to convert a string other than a number to int.Try int(a) and
see what error you get.
You'd have noticed that you don't provide the type of the data you enter in python.By default
python assumes the data type.Though this is helpful, it might lead to some errors at times.Type
checking should be done to avoid errors.
The function type(data) can be used to check the type of data.
>>>type(2)
<class int>
>>>type(2.4)
<class float>
>>>type(hello)
<class str>

Loops
We will discuss two types of loops - the while and for loop.
While loop executes till the conditional statement returns false
>>>x, y = 0, 5
>>>while x < y:
print(x)
x += 1
0
1
2
3

Task:
Type assign x=1 and execute the following code:
while x>0: Print(loop)

Note:To terminate the loop press ctrl+c or restart the shell.Thats what happens when you naively
forget to provide a condition which always evaluates to True. Your program loops and fills you
screen with shit loops.

For
For requires a collection of elements to iterate with.
>>>for letter in loop:
print(letter)
l
o
o
p

Note: Strings are a collection too, we will see about that in the following section.

Input
You can get a user to provide some input so that we can use it for computation later.
the command is called input. The syntax is input(your text).
>>>input(enter any number)
enter any number2
2
>>>x=input(enter any number)
enter any number2
>>>x
2

Task:Try storing twice of the number of the user input.

Note: You might want to do a type casting

Collections
Python has some simple data structures which we can use for having a collection of data.Each
type of these data structures have different properties which will be very useful in using the
language.

Sets
These are unordered collections with no repetitions.
Sets are enclosed in {}.
>>> Set={2,3,s,e,t}

>>>Set
set([2,3,s,e,t])
>>>Set.remove(s)
>>>Set
set([2,3,e,t])
>>>Set.add(4)
set([2,3,4,e,t])

Sets have certain methods which help in altering/analysing the set.

Note:
To view all available methods(more on that later, for now think of them as specific functions) for a
particular Class(more on that later, for now think that these data structures are what we call as a
Class)
dir(name of class)
and to get help about a class or method use

help(name of class)
or
help(class.methodname)
example:
type dir(set)
or
help(set)
then type
help(set.add)

You'll see the documentation for the class or method.


The documentation will have information on what the class/method is about, what parameters are
taken in and what would you can expect by using it.
Task:
create a set b={1,2,3,4}. Assign d=b. remove 4 from d. print both b and d.

Note: The above task gives you an understanding of how the assignment statement woks in
python.Instead to copy a set to another set without altering the original youd want to use the copy
method of sets.

To populate a set we can use use the add method or we can use something like a set
comprehension. These comprehensions can be used to populate a collection with the reference of
other collections
>>> { e**2 for e in {2,3,4}
{16,9,4}

The comprehension simply means { append e to the power 2 to this set for every e belonging to
the set {2,3,4}}
>>> { e**2 for e in {2,3,4,5} if e>2}
{9,16,25}
The above comprehension simply means {append e to the power 2 to this set for every e belonging
to the set {2,3,4,5} if only e>2} this type of comprehension has a filter which checks for a particular
condition to iterate.
>>> {x+y for x in {1,2,3} for y in {2,3,4}}

{3,4,5,6,7}
The above comprehension is what we call double comprehension as it involves iterating over 2
collections and gives combinations of the sum of every x and y.

Task:
Write a set comprehension over {0 to 10} such that the new set consists of the first 0-10 powers of
2

Sets like sets we have in maths, have union and intersection operators. The union operator is
denoted by | (a single line pipe) and the intersection operator is denoted by & (ampersand).

>>> {1,2,3} | {2,3,4,5}


{1,2,3,4,5}
>>> {1,2,3} & {2,3,4,5}
{2,3}
>>> { x*y for x in {1,2,3}|{2,3,4,5} for y in {1,2,3}&{2,3,4,5}}
{2, 3, 4, 6, 8, 9, 10, 12, 15}

>>> {x+y for x in {5,6,7} for y in {6,7,8} if x!=y}


{11,12,13,14,15}
>>>{x*y for x in {0,1,2} for y in {3,6,12} if x!=y}
{0,24,12,6,3}
>>>len({1,2,3})
3
>>>Set={1,2,3}
>>>Set.remove(3) #removes 3
Another useful function is range. Range provides a collection which provides numbers of arithmetic
progressions.
Task:
Create a 5 element set whose elements are product of two disjoint(non-overlapping) sets
containing 3 elements each.Remember sets dont allow repetitions.Try with other numbers apart
from the given example.

Lets try to generate all the possible 3 digit numbers for a given base into a set, this means that for
base 2 the possible numbers would be {0,1,2,3,4,5,6,7}. So for base 10 it'll be {0,1.,999}

>>>base=int(input(enter the base:\n)


>>>digits=set(range(base)) #make sure the numbers are from 0 to base-1
>>>maximum_number_of_digits={ x+ y*base + z*base**2 for x in digits for y in digits for z in digits}

Note: sets are mutable, but the elements of the set should be immutable.

Lists
Lists are a collection go data where order is important and repetitions are allowed.Lists are
enclosed by [].Lists have no limitations on its elements so a list can have a list, a set, a string or
number as its elements.
>>>L=[1,2,3,{4,5},hello,5+3]
>>>L
[1,2,3,{4,5},hello,8]
>>>len(L)

#returns length of the list

6
>>> l=[1,2,3]
>>>sum(l)

#returns the sum of the list

6
>>>l[1]

#returns the element at index 1. Indexing starts from 0 till len(list)-1

2
>>>l.append(4) #appends element 4 to the end of the list
>>>l
[1,2,3,4]
>>> l[1:3] #outputs elements from index 1 till index 3
[2,3]
>>>l[:2] #outputs elements from start till index 2
[1,2]
>>>l[2:] #outputs elements from index 2 till end
[3,4]

>>>l[::2] # outputs elements from start till end with step of 2(skipping 1 element)
[1,3]

Check out dir(list) to see all the methods available for lists.Also try out help(list.method) to check
out the functionality of each method.
Like sets, lists can also be created with simple comprehensions.
>>> [2*x for x in {1,2,3,4}]
[2,4,6,8]
>>>[[x,y] for x in {A,B,C} for y in [1,2,3]] #remember lists can have a list as its element

[['C', 1], ['C', 2], ['C', 3], ['B', 1], ['B', 2], ['B', 3], ['A', 1], ['A', 2], ['A', 3]]
>>>[a,b,c] = [2,4,5]
>>>a

#this is called unpacking a list

2
>>>b
4

To mutate a list we can simply make an assignment statement for that particular index.
>>> l=[1,2,3]
>>> l[2]=4
>>>l
[1,2,4]
>>>dir(list) #check out all the methods for list
>>>help(list.append) #an example to show how to access help for individual methods

Tuples
Tuples are ordered collections which are immutable, meaning that they cannot be changed.This
allows tuples to be elements of sets.Tuples are enclosed by () parenthesis.
>>> t=(1,2,3)

>>>type(t)
<class tuple>
Like lists elements of a tuple can be accessed by indexing or unpacking.
>>> t[1]
2
>>>(x,y) = (1,2)
>>>x
1
>>>S={-3,-2,-1,0,1,2,3,4}
We can make tuples with the help of comprehensions.Lets use S to make a list of all 3 element
tuples (x,y,z) such that x,y,z belong to S and also their sum equals zero
>>>[(x,y,z) for x in S for y in S for z in S if x+y+z==0] #check the output
>>>[(x,y,z) for x in S for y in S for z in S if x+y+z==0][0] # this will provide us with the first tuple
(0,0,0)
>>>dir(tuple)
Task: Try adding another filter such that (0,0,0) is not included.

>>>List(S) #type casting to a list

[-3,-2,-1,0,1,2,3,4]

Task: Try creating a tuple with comprehension as we did with lists.

You'll get a weird output called a generator. This will be covered in the future class.As for now think
of generators as an object which will help us to iterate over(this is similar to range).These will come
handy later when we study Object Oriented Programming and for improving code efficiency.

Dictionaries
A dictionary is a collection of elements which are characterised as key-value pairs.The keys are
immutable, whereas the values can be changed. Dictionaries are denoted by {key:value}.Indexing
a dictionary is by its key.

>>>d={1:one,2:two,3:three}
>>>d[1] #getting the values of the dictionary by its key.
one
>>>listofdict=[{1:one,2:two,3:three},{Apple:red,Orange:orange}] #a list of dictionaries
>>>listofdict[1][Apple]
red
>>>Apple in listofdict[1] #testing for membership
True
>>> {name:name , name:new name}
{name : new name}
As mentioned earlier, keys are immutable but values can be changed.Python will assign only the
last assigned value for a particular key.
All the values and keys of a dictionary can be obtained as shown below.
>>> listofdict[1].values()
dict_values(['red', 'orange'])
>>> listofdict[1].keys()
dict_keys(['Apple', 'Orange'])

Keys can be a tuple.


>>> dictup={(1,2):3,(3,4):5}
>>> dictup
{(1, 2): 3, (3, 4): 5}
>>> dictup.keys()
dict_keys([(1, 2), (3, 4)])
>>> dictup.values()

dict_values([3, 5])

Task: Try creating a variable dictlist, use data from dictum but the keys should be a list and not a
tuple.

Why cant you have lists as keys?


The answer lies with the properties of keys and lists.

Dictionaries can be iterated over with the help of keys.


>>> [x for x in listofdict[1]]
['Apple', 'Orange']

Dictionaries can be created with the help of comprehensions.Lets create a dictionary whose keys
are two element tuples of integers and the values are the sum of the elements of the tuple.
>>> {(x,y):x+y for x in range(10) for y in range(10)} #check the output

Functions
We have seen various data types and collection types.But what if we need to store a chunk of code
which should be executed. Functions are named containers of a block of code.Functions can be
very handy when a particular block of code is needed to be executed many times at different
places, thereby eliminating the need to copy+paste the same code again and again.A function can
be thought of as a set of procedures executed whenever the function is called.
The syntax is
def function_name(inputs to be passed in if any):
block of code

>>> def sayhi():print('hi')


...
>>> sayhi()
hi

Lets make a bigger function,like finding the sum of numbers till x where x is the variable passed
into the function.
>>> def sumofn(x): return x*(x+1)/2

>>> sumofn(10)
55.0
>>> sumofn(3)
6.0
We can make functions which can take multiple arguments and also have some values as
defaults.By having argument defaults we simply use the default value whenever that argument is
not passed.
>>> def powers(x,y=2):

#here y has an argument default of 2

... return x**y


...
>>> powers(4)

#here we are not passing any argument for y, so y takes the default value of 2

16
>>> powers(4,3) # here we have provided a value for y as 3
# which will be taken instead of the default 2
64

Functions can have large code blocks in them, with loops,filters, locally created variables and so
on.
>>>exit()

Additional Information
Python homepage: here
Python Documentation: here
Some cool python scripts : here
Get quick help for your doubts: here
Check out Hour of Code: here
Check out the cool explanation about an algorithm : here

Вам также может понравиться