Sie sind auf Seite 1von 10

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

and not goes together

False and True is False


False and False is False
True or True is True
False or True is True
False or False is False
Packages
From math import
log (which is ln), log10, exp, trig & inverse trig (asin), hyp, sqrt, pi, e

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

the zip function compares 2 lists


list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):


if a>b:
print a
else:
print b
list comprehension syntax
even squares btwn 1 to 11
even_squares = [x**2 for x in range(1,11) if x**2%2==0]

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,

Some for loop things


r = [ 1, 3, 5 ]
for n in r:
print(n)
print(2*n)
print("Finished")
it prints:
1
2
3
6
..

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

DONT FORGET HOW DEF WORKS .

def shut_down(s):

if s == "yes":

return "Shutting down";

elif s == "no":

return "Shutdown aborted";

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)

languages = ["HTML", "JavaScript", "Python", "Ruby"]


print filter(lambda i: i=="Python", languages)
for i in languages:
if i == "Python":
print i

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()

x = linspace(0,10,100) creates 100 divisions between 0 and 10 which is an array of values


sin in numpy works with arrays
sin in math is ordinary sine

Plot a graph from experimental data

0 12121.71
1 12136.44
2 12226.73
3 12221.93
4 12194.13
5 12283.85
6 12331.6
7 12309.25

from numpy import loadtxt


from pylab import plot,show
data = loadtxt("values.txt",float)
x = data[:,0]
y = data[:,1]
plot(x,y)
show()

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")

Python OOP part

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 _ _init_ _(self, name, colour):


self.name = name
self.colour = colour

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

this prints Im a yellow lemon.

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.

lemon is an instance of Fruit and its attributed are name, colour.

Global variables; available everywhere


Member variables; only available to members of a certain class
Instance variable; only available to particular instances of a class

Inheritance

class SubClass(BaseClass) Subclass inherits from base class


class SubClass(BaseClass):
def func(self, whatever):
return super(SubClass,self).func(whatever) (here it doesnt need self)
where func is a function from the SuperClass

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

to class Car add


def drive_car(self):
self.condition = used
print my_car.condition
my_car.drive_car()
print my_car.condition

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

Input & Output

my_list = [i**2 for I in range(1,11)]


f = open(output.txt,w)
for item in my_list:
f.write(str(item) + "\n")

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

my_list = [i ** 2 for i in range(1, 11)]

my_file = open("output.txt", "w")


for i in my_list:
my_file.write(str(i)+"\n")
my_file.close()

reading data

my_file=open("output.txt","r")
print my_file.read()
my_file.close()

OTHER WAY

with open("text.txt", "w") as textfile:


textfile.write("Success!")

with open(file.txt,mode) as variable:


variable.write(whateber)

if variable.closed() == True:
variable.close()

this is useful if we have many files.

Das könnte Ihnen auch gefallen