python programming

Download Python  Programming

Post on 12-Jan-2016

64 views

Category:

Documents

3 download

Embed Size (px)

DESCRIPTION

Python Programming. overview. by. Aliki Muradova. Technical University of Crete. Why Python?. What advantages has it?. Python Programming. The Reasons for Choosing Python. Python is free It is object-oriented It is interpreted It is operating-system independent - PowerPoint PPT Presentation

TRANSCRIPT

Python Programming

Python ProgrammingoverviewbyAliki MuradovaTechnical University of CreteWhy Python?What advantages has it?Python ProgrammingThe Reasons for Choosing PythonPython is freeIt is object-orientedIt is interpretedIt is operating-system independentIt has an excellent optimization moduleIt offers modern COM modules for interfacing with Solids Works

Python ProgrammingGetting Started with PythonPython(x,y) package from http://code.google.com/p/pythonxy The Python(x,y) package comes with all numerical and scientific Python modules. Python(x,y) is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language. Spyder is excellent integrated development environment (IDE). Index for some packages related to python http://pypi.python.org/pypi?%3Aaction=indexSfePy is a software for solving systems of coupled partial differential equations (PDEs) by the finite element method in 2D and 3D http://stepy.org http://plateformesn-m2p.ensam.eu/SphinxDoc/cnem/index.html http://femhub.org/

Python ProgrammingSince Python is an object-oriented language,everything one creates in Python is an object, including integers, float,strings, arrays, etc.>>> i=4>>> x=3.56>>> a=helloExamplesAssociated with objects are methods that act on these objects. ByTyping a dot after the object variable name, we can access a listof methods associated with it. Examples>>> a=hello>>> a.capitalize()HelloBasic ObjectsPython ProgrammingFor integers and floats, it is interpreted as the usual addition; for strings it is interpreted in Python as a concatenation. We can reassign the variables.>>> i=1+2>>> i3>>>a=hello+world!>>>ahello world!>>>a=hello>>>b=a>>>print a,bhello hello>>>b=world!>>>print a,bhello world!

ExamplesBasic ObjectsPython ProgrammingA list is a collection of other Python objects. Lists can contain a varietyof objects (integers, strings, etc). They can contain other list objects as in b= [3,a]. Addition of lists leads to a concatenation as in c=a+a. Thereis an access to individual elements of a list is through the [] operator (asIn a[2]). The indexing of individual elements f a list starts from 0.>>> a=[1, 2, srt]>>> b=[3,a] >>> c=a+a>>> print a,b,c[1, 2, str][3, [1, 2, str]][1, 2, str,1, 2, str]>>> b=a>>>b[2]=3>>>print a[1, 2, 3]>>> range(5)[0, 1, 2, 3, 4]

ExamplesListsPython ProgrammingSimple Python program in the Editor (e.g. within Spyder). You can givea name, e.g. PythonObjects.py, py extension refers to a Python file.# Floats and integersprint 2**10 #2 to the power 10x=0.5print 2.5*x/3# Stringss=Hello World!print 3*s # implies concatenation# Listsa=[0,1,2,3] # list, not an array or vectorb=range(4) # list, with the same contents as aprint a,bprint 3*a # implies concatenationPython ScriptsFile Edit Format Run Options Windows HelpPythonObjects.py-Python ProgrammingThe following output appears in the Console window after running the code PythonObjects.py10240.416666666667Hello World!Hello World!Hello World![0, 1, 2, 3] [0, 1, 2, 3][0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

OutputPython ProgrammingThe following example illustrates the use of for, if and while commands in Python. # Flow control in Pythonfor i in range(10): # does not include 10 if i a=raw_input(Enter data:)Enter data: 3*4-5>>> a'3*4-5'>>> a=input(Enter data:)Enter data: 3*4-5>>> a7

User InputPython ProgrammingThere are numerical objects (arrays, dot product, etc) and methods that are not part of the core Python language, but are part of the numpyand scipy libraries/modules. They are installed when we install Python. However, in order to access them in a script file we must import them.# Using Pylabimport pylab as py #(or e.g. import numpy as py)x=py.array([0,1,2,3]) # creates an array from a listy=x+x # this is now an addition not concatenationprint ya=py.pi # the number 3.1415926535897931theta=py.arange(-a,a,0.1) # sample from -pi to +pi using arangez=py.sin(theta) # compute sin(theta) for all samplesprint sz.max() # find the maximum valueNumerical PythonFile Edit Format Run Options Windows HelpUsingPylab.py-Python ProgrammingThe resulting output in the Console window is shown[0 2 4 6]0.999923257564OutputPython Programming>>> a=3+4j>>> a**2(-7+24j)'>>> sqrt(a) # it is needed to import Numerical Python before(2+1j)

Complex NumbersExamplesPython ProgrammingThere are numerical objects (arrays, dot product, etc) and methods that are not part of the core Python language, but are part of the numpyand scipy libraries/modules. They are installed when we install Python. However, in order to access them in a script file we must import them.# Linear Algebraimport pylab as py #(or e.g. import numpy as py)A=py.array([[2,-1],[-1,2]]) # creates an array from a listB=py.array([1,1])x=py.solve(A,b)print Solution for 2x2 problem is +str(x)Linear AlgebraFile Edit Format Run Options Windows HelpLinearAlgebra.py-Python Programming# Linear Algebra (continuation)Lambda, V=py.eig(A)print Eigenvalues of matrix are +str(Lambda)Print Eigenvectors of matrix are \n +str(V)A=py.rand(50,50)xIn=py.rand(50,1)B=py.dot(A,xIn)xOut=py.solve(A,b)Err=py.norm(xIn-xOut)print Error for a random matrix solve is +str(err)Linear Algebra (cont.)File Edit Format Run Options Windows HelpLinearAlgebra.py-Python ProgrammingPylab supports 2D and 3D plotting via matlibplot(http://matplot.souceforge.net) package that can beAccessed through pylab. PlotsMatLibPlot.py-File Edit Format Run Options Windows Help# 2-D plots using Python/Pylabimport pylab as pypi=py.pix=py.arrange(0,2*pi,pi/50)y=py.sin(x)Z=py.cos(x)py.plot(x,y)py.plot(x,z)py.xlabel(x)py.ylabel(sin(x)&cos(x))py.legend(sin(x),cos(x)))py.savefig(Fig2.png)py.show()Python ProgrammingThe resulting output in the Console window is shownPlots

Python ProgrammingOne can include multiple functions within a single Python file, and Access each one of them individually (a distinct advantage over Matlab).ModulesExample: a file containing multiple functionsSampleFunctions.py-File Edit Format Run Options Windows Help# Module consists of 1-D functions, and derivatives of some of these funcs.import pylab as pydef f1(x): f=-x*py.exp(-x**2) # returns -x*exp(-x**2) return fdef f1_gradient(x): g=-py.exp(x**2)+2*x*x*py.exp(-x**2) # returns the derivative of f return g def f2_hessian(x): h=6*x*py.exp(x**2)-4*x**3*py.exp(-x**2) # return the second derivative of fPython ProgrammingThe resulting output in the Console window is shown below>>> import SimpleFunctions>>> SimpleFunctions.f1(2)-0.036631277777468357ModulesPython ProgrammingPython offers a rich set language features for passing arguments intoFunctions. We consider the function f1 (together with a testing script)Function ArgumentsFunctionsArguments.py-File Edit Format Run Options Windows Help# Example to illustrate function argumentsdef f1(x, a=4, s=hello): print x, a, s

if __name__==__main__: f1(0.3) f1(x=0.4) f1(x=0.5,a=5) f1(0.5, a=5) f1(x=0.6,s=world) f1(0.6,s=world) f1(s=world,a=7,x=0.7)Python ProgrammingThe resulting output in the Console window is shown below0.3 4 hello0.4 4 hello0.5 5 hello0.5 5 hello0.6 4 world0.6 4 world0.7 7 worldFunction ArgumentsPython ProgrammingThere are a few Python quirks that one must keep in mindPython QuirksExamplesPython ProgrammingAn important concept class, in object oriented languages such Python, Is a collection of objects and methods that are closely related. import pylab as pyclass Polynomial: def __init__ (self,aIn): self.a=py.array(aIn)Python Classdef evaluate(x): #v=a[0]+a[1]*x+a[2]*x**2+... v,temp=0.0,1.0 for coeff in a: v+=coeff*temp temp*=x return vif __name__=="__main__": p=Polynomial([1,-1,2]) a=p.a print a st=__str__(); print st p1=evaluate(2.0) print p1 import PolynomialClassfrom PolynomialClass import Polynomialdef __str__(): string=str(a[0]) for i, coeff in enumerate(a[1:]): if coeff == 0.0: continue elif (coeff