Ip Python1
Ip Python1
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Introduction to Python
Oscar Dalmau
December 2013
Outline
1 Overview
2 Basic Syntax
3 Types and Operations
Variable Types
Basic Operators
Numbers, Strings, List, Dictionaries, Tuples and Files
4 Statements and Functions
5 Modules
6 Input/Output
7 Classes and OOP
What is Python?
Python Environment
Python Environment
Python Environment
Python Environment
Run interactive example: print ’Hello world!’
Create the helloworld.py file
#!/Users/osdalmau/anaconda/bin/python
print "Hello, World!"
Create an executable file and run it
$ chmod +x helloworld.py
$./helloworld.py
Script from the Command-line:
$python helloworld.py # Unix/Linux
Importing module:
>>> from sys import path
>>> path.append(’/Users/osdalmau/Dalmau/CIMATMty
/docsTrabajo/Clases/Python/clase1 python/scripts’
>>> import helloworld or
>>> execfile("helloworld.py")
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Basic Syntax
Basic Syntax
Basic Syntax
Basic Syntax
Basic Syntax
Outline
1 Overview
2 Basic Syntax
3 Types and Operations
Variable Types
Basic Operators
Numbers, Strings, List, Dictionaries, Tuples and Files
4 Statements and Functions
5 Modules
6 Input/Output
7 Classes and OOP
Variables
Standard types
Standard types
Python has five standard data types: Numbers, String, List,
Tuple and Dictionary.
List: Lists are the most versatile of Python’s compound
data type A list contains items separated by commas and
enclosed within square brackets ([]). A list can be of
different data type. The values stored in a list can be
accessed using the slice operator ([] and [:]) with indexes
starting at 0 in the beginning of the string and working their
way from -1 at the end. The plus (+) sign is the string
concatenation operator and the asterisk (∗) is the repetition
operator.
Tuple: Tuples contain items enclosed within parentheses
(()) and separated by comma Tuples are read-only Lists
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations Variable Types
Statements and Functions Basic Operators
Modules Numbers, Strings, List, Dictionaries, Tuples and Files
Input/Output
Classes and OOP
Standard types
Function Description
int(x [,base]) Converts x to an integer. base spec-
ifies the base if x is a string, e.g.,
int(’100’,2)==6
long(x [,base] ) Converts x to a long integer. base speci-
fies the base if x is a string.
unichr(x) Converts an integer to a Unicode charac-
ter, e.g., print unichr(345) return ř
ord(x) Converts an integer to a Unicode charac-
ter, e.g., print ord(u ’ř’) return 345
complex(real [,imag]) Creates a complex number.
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations Variable Types
Statements and Functions Basic Operators
Modules Numbers, Strings, List, Dictionaries, Tuples and Files
Input/Output
Classes and OOP
Function Description
dict(d) Creates a dictionary. d must be a se-
quence of (key,value) tuple
eval(str) Evaluates a string and returns an object.
str(x) Converts object x to a string representa-
tion.
chr(x) Converts an integer to a character.
Outline
1 Overview
2 Basic Syntax
3 Types and Operations
Variable Types
Basic Operators
Numbers, Strings, List, Dictionaries, Tuples and Files
4 Statements and Functions
5 Modules
6 Input/Output
7 Classes and OOP
Basic Operators
Operator Type Operators
Arithmetic +, −, ∗, /, ∗∗, %, //
Comparison ==, ! =, <> (! =),>, >=, <, <=
Assignment =, + =, − =, ∗ =, / =, ∗∗ =, % =,
// =
Bitwise &, |,ˆ(xor), ~, <<, >>
Logical and, or, not
Membership in, not in
Identity is, is not (compare the mem-
ory locations of two objects, i.e.,
id(x)==id(y))
See example1basicoperators.py
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations Variable Types
Statements and Functions Basic Operators
Modules Numbers, Strings, List, Dictionaries, Tuples and Files
Input/Output
Classes and OOP
Operators Precedence
Operator Description
∗∗ Exponentiation (raise to the power)
~ Bitwise one complement
∗, /, %, // Multiply, divide, modulo and floor di-
vision
+, − Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise ‘AND’
ˆ, | Bitwise ‘XOR’ and regular ‘OR’
<=, <, >, >= Comparison operators
Operators Precedence
Operator Description
<>, == ! = Equality operators
=, % =, / =, // = Assignment operators
, − =, + =, ∗ =, ∗∗ =
is, is not Identity operators
in, not in Memmership operators
not, or, and Logical operators
Outline
1 Overview
2 Basic Syntax
3 Types and Operations
Variable Types
Basic Operators
Numbers, Strings, List, Dictionaries, Tuples and Files
4 Statements and Functions
5 Modules
6 Input/Output
7 Classes and OOP
Number
Mathematical Functions
Strings
Strings
Every string operation is defined to produce a new string
as its result, because strings are immutable in Python, i.e.,
they cannot be changed in place after they are created. In
other words, you can never overwrite the values of
immutable objects
You can change text-based data in place if you either
expand it into a list of individual characters and join it back
together
>>> S = ’shrubbery’
>>> L = list(S) # convert in a list
>>> L[1] = ’c’ # change a character
>>> ’’.join(L) # join
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations Variable Types
Statements and Functions Basic Operators
Modules Numbers, Strings, List, Dictionaries, Tuples and Files
Input/Output
Classes and OOP
String Methods
String Methods
>>> S = ’1xxx,CIMAT,xxxx,CIMAT,xxxx’
>>> S.startswith(’1xxx’)
>>> where = S.find(’CIMAT’) # Search for position
>>> S.replace(’CIMAT’, ’CimatGto’)
>>> S.capitalize()
>>> S.lower()
>>> S[0].isdigit()
>>> S.split(’,’)
>>> S.rjust(len(S) + 10)
>>> ’SPAM’.join([’eggs’, ’sausage’, ’ham’, ’toast’])
>>> map((lambda x:x.strip()), ’x, y, z’.split(’,’))
>>> [x.strip() for x in ’x, y, z’.split(’,’)]
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations Variable Types
Statements and Functions Basic Operators
Modules Numbers, Strings, List, Dictionaries, Tuples and Files
Input/Output
Classes and OOP
Lists
L = [] # An empty list
L = [123,’abc’,1.23,] #Four items:indexes 0..3
L = [’Bob’, 40.0, [’dev’, ’mgr’]] #Nested sublists
L = list(’spam’) # convert into a list
L = list(range(-4, 4))
L[i] # index
L[i][j] # indexing nested lists
L[i:j] # Slicing
len(L) # length
L1+L2 #Concatenate, repeat, i.e., L=2*L1+3*L2
for x in L: print(x)
3 in L
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations Variable Types
Statements and Functions Basic Operators
Modules Numbers, Strings, List, Dictionaries, Tuples and Files
Input/Output
Classes and OOP
L = [1,2,3]
L.append(4) # Methods: growing, L = [1,2,3,4]
L.extend([5,6]) # L=[1,2,3,4,5,6]
L.append([5,6]) # It is different,L=[1,2,3,4,[5,6]]
L.insert(i, X) # insert object X before index i
L.index(X) # return first index of value
L.count(X) # return number of occurrences of value
L.sort() # sorting, reversing, *IN PLACE*
L.reverse() # reverse *IN PLACE*
L.pop(i) # remove and return item at index
L.remove(X) # remove first occurrence of value
del L[i]
del L[i:j]
L[i:j] = []
L[i] = 3 # Index assignment
L[i:j] = [4,5,6] #slice assignment
L = [x**2 for x in range(5)] # List comprehensions
L = list(map(ord, ’spam’)) # maps
L = list(i**2 for i in range(4))
T = tuple(i**2 for i in range(4))
T = ()
for i in range(4): T +=(i**2,)
Dictionaries
if...else statements
elif Statement
The elif statement allows you to check multiple expressions for
truth value and execute a block of code as soon as one of the
conditions evaluates to true. else and elif statements are
optional.
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else :
statement(s)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
while loop
while expression:
statement(s)
Example:
count = 0
while (count < 9):
print ’The count is:’, count
count = count + 1
Example:
var = 1
while var == 1 : # Infinite loop
num = raw_input("Enter a number :")
print "You enter a number :"
print "You entered: ", num
print "Good bye!"
for loop
Control Description
statement
break Terminates the loop and transfers execution to
the statement immediately following the loop.
continue Causes the loop to skip the remainder of its
body and immediately retest its condition prior
to reiterating.
See example1statements.py
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Functions
Function blocks begin with the keyword def followed by the
function name and parentheses ( ( ) ).
Arguments (parameters) should be placed within these
parenthesis
The first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
Syntax:
def functionname( parameters ):
# ayuda que se obtiene usando help(functionname)
"function_docstring"
function_suite
return [expression] Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Functions
Functions
def mifunc(a,b):
print id(a),id(b)# The same address
as the input parameter.
a=100# Crete a new variable with a new address.
b[0]=10# Modify the first entry.
print id(a),id(b)# b has the same address
as the input parameter.
b=[0,1]# Crete a new variable with a new address.
print id(a),id(b)# The addresses have changed.
x,y=(1,2),(3,4);mifunc(x,y);Error!!
x,y=(1,2),[3,4];mifunc(x,y);Ok!!
Function Arguments
Function Arguments
Variable-length arguments: def func(*targs). args is a
tuple.Try with it! in red is not Ok, Why?
>>>def func1(*args):
s = 0
for i in range(len(args)): s += args[i]
return s
>>> def func2(*args):
s = 0
for i in args[0]: s += i
return s
>>> func1([1,2,3]); func1(1,2,3)
>>> func2([1,2,3]); func2(1,2,3)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Function Arguments
Function Arguments
def mifuncion(**kwargs):
if kwargs.has_key(’Iteraciones’):
Iteraciones=kwargs[’Iteraciones’]
else:
Iteraciones=100
print (’Numero de iteraciones=
{0:4d}’.format(Iteraciones))
mifuncion()
mifuncion(Iteraciones=10)
Function Arguments
Example
>>> def func(a, b = 4, *targs, **kwargs):
print a, b, targs, kwargs
>>>func(3)#a=3,b=4,targs= ,kwargs={}
>>>func(3,10)#a=3,b=10,targs= ,kwargs={}
>>>func(3,10,5)#a=3,b=10,targs=(5),kwargs={}
>>>func(b=10) # Error!!
>>>func(b=10,a=4)#a=4,b=10,targs= ,kwargs={}
>>>func(b=1,a=4,x=4)
#a=4,b=1,targs= ,kwargs={’x’:4}
Function Arguments
Example
>>>func(4,1,1,3,x=4,y=5)
#a=4,b=1,targs=(1,3),kwargs={’x’:4,’y’:5}
>>>func(a=4,b=1,1,3,x=4,y=5) # Error!!
Anonymous function
List Comprehension
Modules
Importing a module
Import Statement
>>> import math
>>> math.cos(math.pi)
from ... import Statement:
>>> from math import cos, pi
>>> cos(pi)
from ... import * Statement:
>>> from math import *
>>> sin(pi), cos(pi)
Locating Modules
Import Statement
>>> import math
>>> math.cos(math.pi)
from ... import Statement:
>>> from math import cos, pi
>>> cos(pi)
from ... import * Statement:
>>> from math import *
>>> sin(pi), cos(pi)
Packages
Files-write
Files-read
Files-read
Files-read
main
if __name__ == "__main__":
muestra_hola()
$ python hola.py (in console)
In []:!python hola.py (in ipython)
Creating Classes
class ClassName:
’Optional class documentation string’
classsuite
Creating Classes
class MyClass:
’Common base class for all MyClass’
mydata = 0
def __init__(self, data): # Constructor
mydata = data
def display(self): ...
def __del__(self): # Destructor
class_name = self.__class__.__name__
print class_name, "destroyed"
The variable mydata is a class variable whose value would
be shared among all instances of the clas
mydata can be accessed as MyClas mydata from inside or
outside the class function
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Creating Classes
The method __init__ is a special method, which is called
class constructor or initialization method that Python calls
when you create a new instance of this clas
The method __del__ , destructor, is invoked when the
instance is about to be destroyed
You declare other class methods like normal functions with
the exception that the first argument to each method is
self, i.e., hex(id(’oftheobjectorinstance’)). Python adds the
self argument to the list for you; you don’t need to include it
when you call the method Note that
>>> myc = MyClass(data)
>>> hex(id(myc))
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Classe
Class Inheritance
you can create a class by deriving it from a preexisting class by
listing the parent class in parentheses after the new class name
class SubClassName (ParentClass1[, ParentClass2, ...
’Optional class documentation string’
class_suite
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
See exampleInterfaseClasse py, ClassExample py: Classes
Parent and Child Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP