Python Summary
Python Summary
Input
print(The value of x is,x)
x=something
z=something else
print(x,z,sep=) gives: value of xvalue of z.
x=float(input(Enter the value of x: ))
Arithmetic
x//y integer part of x divided by y
x%y remainder after x is divided by y. modulo
x+=1 add 1 to x
x*=-2.6 multiply x by -2.6
Booleans
not is evaluated first;
and is evaluated next;
or is evaluated last
Controlling stuff
If x==1: (also >=, <=)
if x!=1: check if x is not equal to 1.
If x>10:
print()
Elif x>9
Print()
else:
print(..)
While
x=int(input(.)
while x>10:
print(Not good etc)
x=int(input(Enter.)
print(your number is x)
with same while start, if x==1:
break
x= 34gg
Dictionaries
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
adding values to a dictionary dict_name[new_key] = new_value
del dict_name[key_name]
print (residents['Sloth']) prints the thing belonging to Sloth from the dictionary residents
Lists
r=[1,2.5,3]
also r=[x,y,z] where x,y,z are pre-defined. If value of x later changes, r will still have the
same 1st element.
r[1]=3.5 changes the 2nd element of the list
total=sum(r)
print(total) adds up all the values in the list
other useful functions: min(r), max(r), len(r) calculates number of elements in a list
map(log,r) takes the natural logarithm of each element of a list r in turn. Map allows us to use
ordinary functions on all the elements of a list at once. Normally the new values would be
converted to a new list:
logr=list(map(log,r))
r.append(6.1) adds 6.1 at the end of list r
r.pop() removes last element, r.pop(n) removes nth element.
n.remove(item) will remove the actual item if it finds it n.remove(3) removes 3 from the list
wherever it is
del(n[1]) is like .pop in that it will remove the item at the given index, but it won't return it
animals.insert(1, "dog")
We insert "dog" at index 1, which moves everything down by 1
animals = ["ant", "bat", "cat"]
print (animals.index("bat"))
Then, we print the first index that contains the string "bat", which will print 1
square_list.sort() sorts the elements of square list into alphabetical or numerical order.
In a for loop:
for i in range(len(numbers)) : this goes through all the elements of a list called numbers
slicing a list
print list[start:end:stride] stride = space btwn items in sliced list
Arrays
Number of elements is fixed; elements must be of the same type
Creating arrays
From numpy import zeros
a=zeros(4,float)
print (a) gives [0.0.0.0.]
Or a=zeros([3,4]),float) which gives a 3x4 zero matrix.
Or convert a list to an array say r=[1,2,3]
a=array(r,float) or a=array([1,2,3],float)
2D arrays: a=array([[1,2,3],[4,5,6]],float)
2D arrays have elements a[0,1]=1 this changes the second element in the 1st raw
Loading array from a text file
from numpy import loadtxt
a=loadtxt(values.txt,float) (values.txt has to be in the folder where the program is saved)
Dot product
From numpy import array, dot
a=array([
b=array([
print(dot(a,b))
Matrix multiplication print(dot(a,b)) where a and b are matrices
Applying functions to arrays
B=array(map(sqrt,a),float) (it is converted back to an array)
Instead of len, there is size and shape for matrices.
Print(a.size) tells total number of elements and (a.shape) tells dimensions
Slicing
r[m:n] is list composed of a
subset of the elements of r, starting with element m and going up to but not
including element n.
from numpy import array
a = array([2,4,6,8,10,12,14,16],int)
b = a[3:6]
print(b)
[ 8 10 12]
You can write r[2:], which means all elements of the list from element
2 up to the end of the list,
Range function
r = range(5)
for n in r:
print(n**2)
0
1
4
9
16
Evaluating a sum
Sum of 1/k from 1 to 100.
s = 0.0
for k in range(1,101):
s += 1/k
print(s)
for i in range(len(numbers)): (it iterates through every element of a list)
Importing data
from numpy import loadtxt
values = loadtxt("values.txt",float)
s = 0.0
for x in values:
s += x**2
print(s)
Def function
Typing
def shut_down(s):
if s == "yes":
elif s == "no":
else:
return "Sorry"
lambda x: x % 3 == 0
Is the same as
def by_three(x):
return x % 3 == 0
my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)
Plotting graphs
from pylab import plot,show
x = [ 0.5, 1.0, 2.0, 4.0, 7.0, 10.0 ]
y = [ 1.0, 2.4, 1.7, 0.3, 0.6, 1.8 ]
plot(x,y)
show()
0 12121.71
1 12136.44
2 12226.73
3 12221.93
4 12194.13
5 12283.85
6 12331.6
7 12309.25
ylim(-1.1,1.1) to change the y range of the graph. Ylim is part of pylab. the ylim statement
has to come after the plot statement but before the show statement
xlabel("x axis")
An object is a single data structure that contains data & functions; the functions of an object
are called its methods. Attributes also exist.
For example
Class Fruit(object):
A class that makes fruits
def description(self):
print Im a %s %s. %(self.colour, self.name)
lemon = Fruit(lemon,yellow)
lemon.description
lemon.function() if the function has arguments other than self
def _ _ init _ _() is a function required for classes & initialises the objects it creates.
Init always takes at least 1 argument; self, that refers to the object being created.
Inheritance
example
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
my_car.display_car()
look at str(self.mpg)
modifying variables
for the 2nd time itll print used, for a reason you need driva_car() with brackets.
Repr:
class Point3D(object):
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point=Point3D(1,2,3)
print my_point
f.close()
w stands for write, we stored the result of this operation in the file object, f. (f could be
anything)
r+ = read and write mode
reading data
my_file=open("output.txt","r")
print my_file.read()
my_file.close()
OTHER WAY
if variable.closed() == True:
variable.close()