Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome, Safari or Firefox browser.

Python Workshop

Let's Enjoy Scientific Computing!

A Workshop presented by: Shayan Fahimi

  • Get to Know Python!
  • Spelling and Grammer
  • Group Power
  • Make It Your Own
  • Coding is Easier than Ever
  • Knowledge
  • Declerative Knowledge : Statement of Facts
  • “The square root of number x is a number y such that y*y = x”
  • Imperative knowledge : “how to” methods or recipes
  • Start with a guess, called g!
  • If g*g is close enough to x, stop and say that g is the answer.
  • Otherwise make a new guess, by averaging g and x/g!
  • Using this new guess, repeat the process until we get close enough
  • Algorithms are recipes.

    A Basic Machine Structure

    Turing showed that using six primitives, can compute anything.

    Modern programming languages have more convenient set of primitives.

    Options for Programming Languages

    Low Level Languages

    Similar Instructions to internal control unit.

  • Move data from one location to another
  • Execute a simple ALU operation
  • Very low level programming

    High Level Languages

    Compiler Languages:

    Interpreter Languages:

    History of Python
  • Python was conceived in the late 1980s.
  • Its implementation was started in December 1989 by Guido van Rossum.
  • Python 2.0 was released on 16 October 2000, with many major new features including support for unicode.
  • Python 3.0, a major, backwards-incompatible release, was released on 3 December 2008 after a long period of testing
  • Why Python?
  • Holistic Language Design
  • Readability
  • Balance of High Level and Low Level Programming
  • Language Interoperability
  • Documentation System
  • Hierarchical Module System
  • Data Structures
  • Available Libraries
  • But there are some Downsides!!!

    What is created with Python?

    Mainly programmed with Python:

  • Bittorrent
  • Deluge
  • Dropbox
  • Ubuntu Software Center
  • Kivy
  • Embedded as a scripting language:

  • Abaqus
  • Autodesk Maya
  • FreeCad
  • Gedit
  • MSC. Software (Adams, …)
  • Notepad++
  • Python IDE
    There are different python distributions which are based on the libraries that each of them has and the IDE:
  • Sage
  • PythonXY
  • Enthought Canopy
  • Anaconda
  • Spelling and Grammer

    Python has a meaningful and easy to read Syntax

    		>>>print("Hello World!")
    		>Hello World!
    Data Objects

    Everything is Object!

    There are two groups of objects:

  • Scalar: can not be subdivided into simpler structures
  • 	   >>>type(3.0)
  • Non-Scalar : have internal structure
  • 	   >>>type("salam")
    	   >>>type([1, 2, 3])
    Slicing, Overloading and Casting

    You can cast types of objects:


    Many operators are overloaded:

    		>>>print(3 * "a") 
    		>>>print("a" + "bc")

    Slicing is easier than ever:

    Basic Operators
  • Arithmetic operators
  • 			>>>k = 1.0 + (3.0**2.0) + 4.0 * 12.0		
    			>>>m = 3 % 2 + 3 / 2
  • Comparison operators
  • 			>>>k = (2 == 5)		
    			>>>m = (3 >= 7)
  • Boolean operators
  • 			>>>k = True and not False		
    			>>>m = False or True

    The operators in and not in test for collection membership

    Conditional Statements

    The indentation denotes a block of instructions, this indentation provides a visual structure that reflects the semantic structure of the program.

    		#My comments will be here!
    		if x%2 == 0:
    			if x%3 == 0:
    				print('Divisible by 2 and 3')
    				print('Divisible by 2 and not by 3')
    		elif x%3 == 0:
    			print('Divisible by 3 and not by 2')

    We can repeat a sequence of steps multiple times based on some decision.

    Leads to new classes of algorithms

    		x = 3
    		ans = 0
    		itersLeft = x
    		while (itersLeft != 0):
    			ans = ans + x
    			itersLeft = itersLeft – 1
    		print(str(x) + '*' + str(x) + ' = ' + str(ans))
    For Loops

    A For loop is defined as follows:

    		for < identifier > in < sequence >:
    			< code block > 

    A sequence of Intergers for iteration can be generated by:

    		range(n) = [0, 1, 2, 3, …, n-1]
    		range(m,n) = [m, m+1, …, n-1]

    Functions give us abstraction

    		def < function name > (< formal parameters >):
    			< function body > 

    A simple example:

    		def max(x, y):
    			if x > y:
    				return x
    				return y

    It can be invoked by:

    		>>>z = max(3, 4)

    All Functions and script can be considered as modules.

    They can be imported separately or as a group.

    		pi = 3.14159
    		def area(radius):
    			return pi*(radius**2)
    		def circumference(radius):
    			return 2*pi*radius

    Assume we save it as, then it can be imported by:

    		import cicle as crl
    		from  circle import area
    		from circle import *

    Reduce a problem to a simpler version of the same problem: Recursive Step

    Keep Reducing until reach a simple case that can be solved directly: Base Step.

    		def recurMul(a, b):
    			if b == 1:
    				return a
    				return a + recurMul(a, b-1)

    Global Variables:

    		>>>global numCalls

    Use with care!!!


    What if we hit an unexpected condition?

  • Trying to access beyond the limits of a list will raise an IndexError
  • Trying to convert an inappropriate type will raise a TypeError
  • Referencing a non-existing variable will raise a NameError
  • Mixing data types without appropriate coercion will raise a TypeError
  • What to do?

  • Fail silently
  • Return an “error” value
  • Stop execution, signal error condition
  • Dealing with Exceptions
    			f = open(‘grades.txt’)
    			# … code to read and process grades
    			raise Exception('Can’t open grades file')

    The most General Form:

    		def divide(x, y):
    				result = x / y
    			except ZeroDivisionError, e:
    				print "division by zero! " + str(e)
    				print "result is", result
    				print "executing finally clause"
    Group Power

    One of the powerful characteristics of Python is its huge Data Types

  • Tuples
  • Lists
  • Dictionaries
  • Sets
  • Tuples

    Ordered Sequence of Elements

    Elements can be (I think) anything:

    		t1 = (1, ‘two’, 3)
    		t2 = (t1, ‘four’) 


  • Concatenation
  • Indexing
  • Slicing
  • Singletons
  • 		print(t1+t2)
    		t3 = (‘five’,)
    Manipulating Tuples

    The Empty Tuple can be defined by:

    		divisors = ()

    You can iterate over Tuples.

    Tuples can not be changed after creation.

    They are particularly good for keeping a set of known and fixed number of other data object, such as space coordinates.


    A lot like Tuples.

  • Ordered Sequence of Values, each identified by an index.
  • Use Hard Brackets instead of Parentheses.
  • Slicing
  • Singletons are now just [4] rather than (4, )
  • BUT

    Lists are Mutable!

    Structure of Lists
    		M = ['Ali', 'Shahab']
    		F = ['Marzie', 'Niloofar']
    		Name = [M, F]
    		Name1 = [['Ali', 'Shahab'],
    			['Marzie', 'Niloofar']]
    		Name=[['Ali', 'Shahab', 'MohammadReza'],
    			['Marzie', 'Niloofar']]
    		Name1=[['Ali', 'Shahab'], ['Marzie', 'Niloofar']]

    Elements in Name are not copies of the lists, they are the lists themselves.

    We can also change elements directly:

    Operations on Lists

    Lists are iteratable like Tuples and Strings.

    Many operations can be performed on Lists:

  • Appending
  • 		Name = M.append(F)
    		[['Ali', 'Shahab'], ['Marzie', 'Niloofar']]
  • Flattening
  • 		Name = M + F
    		['Ali', 'Shahab', 'Marzie', 'Niloofar']
  • Cloning
  • 		Name1 = Name[:]

    Avoid Mutating a list over which one is iterating.

    It will result in errors or infinity loops.


    Inside for loops, Python keeps track of where it is in list using internal counter. Mutating changes the length, but do not update the counter.


    Dict is generalization of lists.

    Here, indices are refered to as Keys, having arbitrary form.

    A Dict is a collection of < key, values >.

    		 monthNumbers = { ‘Jan’:1, ‘Feb’:2, ‘Mar’:3,
    		 1:’Jan’, 2:’Feb’, 3:’Mar’} 

    We can access Values by using Keys.

    Operations of Dicts
  • Insertion:
  • Iteration:
  • keys() and values() method:
  • 		monthNumbers[‘Apr’] = 4
    		collect = []
    		for e in monthNumbers:
    		[1, 2, 'Mar', 'Feb', 'Apr', 'Jan', 3]
    		[1, 2, 'Mar', 'Feb', 'Apr', 'Jan', 3]

    Keys can be another complex object such as Tuples. Keys must be immutable.


    Sets are unordered lists with no duplicate entry.

    They can be used to calculate differences and intersections.

    		a = set(["Jake", "John", "Eric"])
    		b = set(["John", "Jill"])
    		set(['Jake', 'Eric'])
    		 set(['Jill', 'Jake', 'John', 'Eric'])
    Functions as Objects

    Functions are also Objects:

  • They have types.
  • They can be elements of data structures
  • They can appear in expressions.
  • It will result in Higher order Programming.

    		def applyToEach(L, f):
    			for i in range(len(L)):
    				L[i] = f(L[i])
    		L = [1, -2, 3.4]
    		applyToEach(L, abs)
    		applyToEach(L, int)
    		applyToEach(L, fact)

    Python provides a general purpose HOP called map

    		map(abs, [1, -2, 3, -4])
    		[1, 2, 3, 4]

    Python supports the creation of anonymous functions

    		def f(x):
    			return x*2
    		g = lambda x: x*2
    Object Oriented Programming

    Python supports many different kinds of data.

    Objects have:

  • A type (a particular object is said to be an instance of a type)
  • An internal data representation (primitive or composite)
  • A set of procedures for interaction with the object
  • In OOP, Everything is an object and has a type. It will help in data obstraction.

    New Types

    In Python, the class statement is used to define a new type.

    		class Coordinate(object):
    			… define attributes here

    Classes can inherit attributes from other classes

    __init__ method provides a way to add some initial values:

    		class Coordinate(object):
    			def __init__(self, x, y):
    				self.x = x
    				self.y = y

    self is the name of the passed object by the Python.

    The “.” operator is used to access an attribute of an object

    		#creating an instance
    		origin = Coordinate(0,0)
    Methods in Types

    Left to its own devices, Python uses a unique but uninformative print presentation for an object

    		>>> print c
    		<__main__.Coordinate object at 0x7fa918510488>

    __str__ method for a class will be called when it needs a string to print.

    		class Coordinate(object):
    			def __init__(self, x, y):
    				self.x = x
    				self.y = y
    			def __str__(self):
    				return “<”+self.x+”,”+self.y+”>”
    		>>> print c
    Methods in Types

    Use methods for getting and setting values in types. Otherwise, there will be bugs.

    		class Coordinate(object):
    			def __init__(self, x, y):
    				self.x = x
    				self.y = y
    			def __str__(self):
    				return “<”+self.x+”,”+self.y+”>”
    			def get(self):
    				return (self.x, self.y)
    			def set(self, e):
    				self.x = e[0]
    				self.y = e[1]
    Python Libraries

    Python has plenty of Open-source libraries:

  • Numpy: adds vectors, matrices, and many high-level mathematical functions
  • Scipy: adds mathematical classes and functions useful to scientists
  • MatPlotLib: adds an object-oriented API for plotting
  • PyLab: combines the other libraries to provide a MATLAB-like interface
  • Creating Plots

    pylab must be imported before use.

    Plots can be created by pylab.plot

  • The first two arguments to pylab.plot must be sequences of the same length.
  • First argument gives x-coordinates.
  • Second argument gives y-coordinates.
  • Points plotted in order. As each point is plotted, a line is drawn connecting it to the previous point.
  • An Example of Plot
    		pylab.title('Monthly Temperature of City) 
    		pylab.ylabel('Temperature (C)')
    		pylab.legend(loc = 'best')
    		pylab.plot(M, T)

    Also, pylab.hist() will make histograms!

    Random Number will generate suedo-random numbers!

  • random.seed([x]): Initialize the basic random number generator.
  • random.randint(a, b): Return a random integer N such that a<=N<=b.
  • random.choice(seq): Return a random element from the non-empty sequence seq.
  • random.random(): Return the next random floating point number in the range [0.0, 1.0).
  • random.uniform(a, b): Return a random floating point number N such that a<=N<=b for a<=b and b<=N<=a for b< a.
  • Scientific Computing

    NumPy is the fundamental package for scientific computing with Python. It contains:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities
  • Numpy Capabilities
  • ndarray: is a (usually fixed-size) multidimensional container of items of the same type and size.
  • 	import numpy as np
    	x = np.array([[1, 2, 3], [4, 5, 6]])
  • numpy.matrix[source]: Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).
  • 	a = np.matrix('1 2; 3 4')
    	np.matrix([[1, 2], [3, 4]])
    Numpy Capabilities

    numpy.linalg: is a comprehensive set of Python methods for algebrical operations.

  •[a, b]: Dot product of two arrays.
  • linalg.cholesky(a): Cholesky decomposition.
  • linalg.svd(a[, full_matrices, compute_uv]): Singular Value Decomposition..
  • linalg.eig(a): Compute the eigenvalues and right eigenvectors of a square array.
  • linalg.solve(a, b): Solve a linear matrix equation, or system of linear scalar equations.
  • linalg.inv(a): Compute the (multiplicative) inverse of a matrix.
  • 	a = np.matrix('1 2; 3 4')
    	np.matrix([[1, 2], [3, 4]])

    At the moment, the current combination of Python, NumPy, SciPy, Matplotlib, and IPython provide a compelling environment for numerical analysis and computation.

    Pylab will bring all of these environments in one place.

    For example, polyfit which is a function in pylab will fit a polynominal of degree n to the correspondant values.

    pylab.polyfit(xvals, yvals, degree)

    Python Workshop By Shayan Fahimi