1 / 30

Python Programming

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

kyrene
Télécharger la présentation

Python Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python Programming overview by Aliki Muradova Technical University of Crete

  2. Why Python? What advantages has it?

  3. Python Programming The Reasons for Choosing Python • Python is free • It is object-oriented • It is interpreted • It is operating-system independent • It has an excellent optimization module • It offers modern COM modules for interfacing with Solids Works

  4. Python Programming Getting Started with Python • Python(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=index • SfePy 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/

  5. Python Programming Basic Objects Since Python is an object-oriented language, everything one creates in Python is an object, including integers, float, strings, arrays, etc. Examples >>> i=4 >>> x=3.56 >>> a=“hello” Associated with objects are methods that act on these objects. By Typing a ‘dot’ after the object variable name, we can access a list of methods associated with it. Examples >>> a=“hello” >>> a.capitalize() ‘Hello’

  6. Python Programming Basic Objects For 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. Examples >>> i=1+2 >>> i 3 >>>a=“hello”+“world!” >>>a “hello world!” >>>a=“hello” >>>b=a >>>print a,b hello hello >>>b=“world!” >>>print a,b hello world!

  7. Python Programming Lists A list is a collection of other Python objects. Lists can contain a variety of 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. There is an access to individual elements of a list is through the [] operator (as In a[2]). The indexing of individual elements f a list starts from 0. Examples >>> 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]

  8. Python Programming Python Scripts Simple Python program in the Editor (e.g. within Spyder). You can give a name, e.g. PythonObjects.py, ‘py’ extension refers to a Python file. • PythonObjects.py-… • File Edit Format Run Options Windows Help # Floats and integers print 2**10 #2 to the power 10 x=0.5 print2.5*x/3 # Strings s=“Hello World!” print 3*s # implies concatenation # Lists a=[0,1,2,3] # list, not an array or vector b=range(4) # list, with the same contents as a print a,b print 3*a # implies concatenation

  9. Python Programming Output The following output appears in the Console window after running the code PythonObjects.py 1024 0.416666666667 Hello World!HelloWorld!Hello World! [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

  10. Python Programming Flow Control The following example illustrates the use of ‘for’, ‘if’ and ‘while’ commands in Python. • FControl.py-… • File Edit Format Run Options Windows Help # Flow control in Python for i in range(10):# does not include 10 if i<=4: print i, i**2 elifi<=7: print i,i**2+1 else: print i,i**2+2 s='-' while len(s)<25: s+='-' print s

  11. Python Programming Output The following output appears in the Console window after running the code FControl.py 0 0 1 1 2 4 3 9 4 16 5 26 6 37 7 50 8 66 9 83 -------------------------

  12. Python Programming User Input Python provides two commands, namely ‘raw_input’ and ‘input’ for user. The first command returns the user input as a string, while the second Command will interpret and evaluate the input, and return the interpreted value if the evaluation is meaningful. >>> a=raw_input(“Enter data:”) Enter data: 3*4-5 >>> a '3*4-5' >>> a=input(“Enter data:”) Enter data: 3*4-5 >>> a 7

  13. Python Programming Numerical Python There are numerical objects (arrays, dot product, etc) and methods that are not part of the core Python language, but are part of the numpy and scipy libraries/modules. They are installed when we install Python. However, in order to access them in a script file we must import them. • UsingPylab.py-… • File Edit Format Run Options Windows Help # Using Pylab import pylab as py#(or e.g. import numpy as py) x=py.array([0,1,2,3]) # creates an array from a list y=x+x# this is now an addition not concatenation print y a=py.pi# the number 3.1415926535897931 theta=py.arange(-a,a,0.1)# sample from -pi to +pi using arange z=py.sin(theta) # compute sin(theta) for all samples print sz.max() # find the maximum value

  14. Python Programming Output The resulting output in the Console window is shown [0 2 4 6] 0.999923257564

  15. Python Programming Complex Numbers Python also supports the use of complex numbers through the use of symbol “j” that represents . Examples >>> a=3+4j >>> a**2 ‘(-7+24j)' >>> sqrt(a) # it is needed to import Numerical Python before ‘(2+1j)

  16. Python Programming Linear Algebra There are numerical objects (arrays, dot product, etc) and methods that are not part of the core Python language, but are part of the numpy and scipy libraries/modules. They are installed when we install Python. However, in order to access them in a script file we must import them. • LinearAlgebra.py-… • File Edit Format Run Options Windows Help # Linear Algebra import pylab as py#(or e.g. import numpy as py) A=py.array([[2,-1],[-1,2]]) # creates an array from a list B=py.array([1,1]) x=py.solve(A,b) print “Solution for 2x2 problem is” +str(x)

  17. Python Programming Linear Algebra (cont.) • LinearAlgebra.py-… • File Edit Format Run Options Windows Help # 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)

  18. Python Programming Plots Pylab supports 2D and 3D plotting via matlibplot (http://matplot.souceforge.net) package that can be Accessed through pylab. • MatLibPlot.py-… • File Edit Format Run Options Windows Help # 2-D plots using Python/Pylab import pylab aspy pi=py.pi x=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()

  19. Python Programming Plots The resulting output in the Console window is shown

  20. Python Programming Modules One can include multiple functions within a single Python file, and Access each one of them individually (a distinct advantage over Matlab). Example: a file containing multiple functions • SampleFunctions.py-… • File Edit Format Run Options Windows Help # Module consists of 1-D functions, and derivatives of some of these funcs. importpylabaspy def f1(x): f=-x*py.exp(-x**2) # returns -x*exp(-x**2) return f def 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 f

  21. Python Programming Modules The resulting output in the Console window is shown below >>> importSimpleFunctions >>> SimpleFunctions.f1(2) -0.036631277777468357

  22. Python Programming Function Arguments Python offers a rich set language features for passing arguments into Functions. We consider the function f1 (together with a testing script) • FunctionsArguments.py-… • File Edit Format Run Options Windows Help # Example to illustrate function arguments deff1(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)

  23. Python Programming Function Arguments The resulting output in the Console window is shown below 0.3 4 hello 0.4 4 hello 0.5 5 hello 0.5 5 hello 0.6 4 world 0.6 4 world 0.7 7 world

  24. Python Programming Python Quirks There are a few Python ‘quirks’ that one must keep in mind Examples >>> 5.0/2 2.5 >>> 5/2 2 >>> from __future__ import division >>> 5/2 2.5 >>> A=array([[2,1],[1,2]]); x=array([1,-1]) >>> b=A*x >>> b array([[2,-1], [1,-2]]]) # the ‘*’operator is interpreted as >>> b=dot(A,x) >>> b array([1,-1]) # the ‘dot’ operator is interpreted as

  25. Python Programming Python Class An important concept “class”, in object oriented languages such Python, Is a collection of objects and methods that are closely related. • PolynomialClass.py defevaluate(x): #v=a[0]+a[1]*x+a[2]*x**2+... v,temp=0.0,1.0 forcoeffin a: v+=coeff*temp temp*=x return v if __name__=="__main__": p=Polynomial([1,-1,2]) a=p.a print a st=__str__(); printst p1=evaluate(2.0) print p1 importpylabaspy classPolynomial: def__init__ (self,aIn): self.a=py.array(aIn) importPolynomialClass fromPolynomialClassimport Polynomial def__str__(): string=str(a[0]) fori, coeffinenumerate(a[1:]): ifcoeff == 0.0: continue elif(coeff<0): sign=' - ' else: sign=' + ' string+=sign+str(abs(coeff))+’*x^’+str(i+1) return string

  26. Python Programming SfePy- software for solving PDEs in Python • SfePy is a software for solving systems of coupled partial differential equations (PDEs) by the finite element method in 2D and 3D • SfePycan use many terms to build systems of partial differential equations (PDEs) to be solved • SfePycomes with a number of examples that can get you started • Sources :http://sfepy.org , http://femhub.org/ http://plateformesn- m2p.ensam.eu/SphinxDoc/cnem/index.html

  27. biot/biot.py Biot problem - deformable porous mediumm With using modules/lib.: numpy, sfepy

  28. biot/biot_npbc.py Biot problem - deformable porous medium with the no-penetration boundary condition on boundary region With using modules/libraries: sfepy.linalg, sfepy.mechanics.matcoefs

  29. linear_elasticity/linear_viscoelastic.py Linear viscoelasticity with pressure traction load on surface and constrained to one-dimensional motion. The fading memory terms require an unloaded initial configuration, so the load starts in the second time step. With using modules/libraries sfepy.base.base sfepy.mechanics.matcoefs sfepy.homogenization.utils

  30. Python Programming References • Mark Lutz & David Ascher, Learning Python, O’Reilly, 1999 (Help for Programmers) • Mark Lutz, Programming Python, O’Reilly, 2001 (Solutions for Python Programmers) • Documentations from internet sources

More Related