Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Introduction to Python
Oscar Dalmau
Centro de Investigación en Matemáticas
CIMAT A.C. Mexico
December 2013
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
What is Python?
Python is a high-level, interpreted, interactive and
object-oriented scripting language.
Python is Interpreted: You do not need to compile your
program before executing it.
Python is Interactive: One can interact with the interpreter
or the prompt directly to write your program
Python is Object-Oriented: i.e. Python supports
Object-Oriented style
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Some Python Features
Portable: Python can run on a wide variety of hardware
platforms and has the same interface on all platform
Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to
or customize their tools to be more efficient.
Databases: Python provides interfaces to all major
commercial database
GUI Programming
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Some Python Features
It supports functional and structured programming
methods as well as OOP.
It can be used as a scripting language or can be compiled
to byte-code for building large application
Supports automatic garbage collection.
It can be integrated with C, C++ and Java.
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Python Environment
Python is available on a wide variety of platforms: Unix (Solaris,
Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.), Win
9x/NT/2000, Macintosh (Intel, PPC, 68K) etc
Install Python?
Running Python.
Interactive Interpreter
$python # Unix/Linux
or
C:>python # Windows/DOS
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Python Environment
Python is available on a wide variety of platforms including
Linux and Mac OS X: Unix (Solaris, Linux, FreeBSD, AIX,
HP/UX, SunOS, IRIX, etc.), Win 9x/NT/2000, Macintosh (Intel,
PPC, 68K) etc
Install Python?
Running Python.
Script from the Command-line:
$python script.py # Unix/Linux
C:>python script.py # Windows/DOS
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Python Environment
Python is available on a wide variety of platforms including
Linux and Mac OS X: Unix (Solaris, Linux, FreeBSD, AIX,
HP/UX, SunOS, IRIX, etc.), Win 9x/NT/2000, Macintosh (Intel,
PPC, 68K) etc
Install Python?
Running Python.
IDE: IDLE, Spyder, etc (Unix/Macintosh), PythonWin,
Spyder, etc (Windows)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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
Python Identifiers: A Python identifier is a name used to
identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Reserved Words: and, assert, break, class, continue, def,
del, elif, else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise, return, try,
while, with, yield
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Basic Syntax
Lines and Indentation: There are no braces to indicate
blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation.
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount.
Multi-Line Statements: Python allows the use of the line
continuation character (\), but statements contained within
the [], {} or brackets do not need to use the line
continuation character
See example1basicsyntax.py
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Basic Syntax
Quotation in Python: Python accepts single ('), double ('')
and triple (''' or '''''' ) quotes to denote string literal The triple
quotes can be used to span the string across multiple lines.
Comments in Python: A hash sign (#) that is not inside a
string literal begins a comment.
Blank Lines: A line containing only whitespace, possibly
with a comment, is known as a blank line and Python
ignores it.
Multiple Statements on a Single Line: The semicolon (;)
allows multiple statements on the single line
See example2basicsyntax.py
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Basic Syntax
Multiple Statement Groups as Suites: A single code
block is called a suite. Statements, such as if, while, def,
and class require a header line and a suite. Header lines
begin the with the keyword and terminate with a colon ( : )
and are followed by a code block (the suite)
if expression :
suite
elif expression :
suite
else :
suite
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Basic Syntax
Accessing Command-Line Arguments: The Python sys
module provides access to any command-line arguments
(using sys.argv):
sys.argv: List of command-line arguments, sys.argv[0] is
the program or the script name.
len(sys.argv): Number of command-line argument
See example3basicsyntax.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
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
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
Variables
Variables are memory locations to store value. When we create
a variable one reserves some space in memory
Assigning Values to Variables:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
Multiple Assignment:
>>> x = y = z = 10
>>> a, b, txt = 1,4,’hello’
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
Python has five standard data types: Numbers, String, List,
Tuple and Dictionary.
Numbers: Python supports four numerical types i.e., int,
long, float and complex
String: Strings are identified as a contiguous set of
characters in between quotation marks (single or double).
Subsets of strings 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.
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
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
Python has five standard data types: Numbers, String, List,
Tuple and Dictionary.
Dictionary: Dictionaries are kind of hash table type and
consist of key-value pairs. A dictionary key can be almost
any Python type, but are usually numbers or string Values
can be any arbitrary Python object. Dictionaries are
enclosed by curly braces ({}) and values can be assigned
and accessed using square braces ([]).
See example1standardtypes.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
Data Type Conversion
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
Data Type Conversion
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.
Other functions: float(x), tuple(s), list(s) ,set(s), hex(x), oct(x)
See example1datatypeconversion.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
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
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
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
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
<>, == ! = Equality operators
=, % =, / =, // = Assignment operators
, − =, + =, ∗ =, ∗∗ =
is, is not Identity operators
in, not in Memmership operators
not, or, and Logical operators
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
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
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
Number
Number data types store numeric value They are
immutable data types which mean that changing the value
of a number data type results in a newly allocated object.
Number objects are created when you assign a value to
the
>>> a = 3; print ’(’, a, ’,’, id(a), ’)’
>>> a = 4; print ’(’, a, ’,’, id(a), ’)’
You can also delete the reference to a number object by
using the del statement
del var1[,var2[,var3[....,varN]]]]
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
Number Type Conversion
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with
real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number
with real part x and imaginary part y. x and y are numeric
expressions
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
Mathematical Functions
acos asinh atanh cos e exp
frexp hypot ldexp log10 pi sin
acosh atan ceil cosh erf expm1
fsum isinf lgamma log1p pow sinh
asin atan2 copysign degrees erfc fabs
gamma isnan log modf radians sqrt
factorial tan floor tanh fmod trunc
>>> import math
>>> math.cos(math.pi)
>>> dir(math) # getting help
>>> help(math) # getting help
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
Strings
Strings are amongst the most popular types in Python. We
can create them simply by enclosing characters in quote
Python treats single quotes the same as double quote
>>> a = ’Hello’
>>> a = "Hello World!"
They are our first example of a sequence, ie, a positionally
ordered collection of other object Strictly speaking, strings
are sequences of one-character strings; other, more
general sequence types include lists and tuples.
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
Strings: sequence operations
We can access to elements of the string (charactes and/or
substring) by using [] bracket, and the indexing and slicing
operation.
Python offsets start at 0 and end at one less than the
length of the string.
Python also lets you fetch items from sequences such as
strings using negative offset. You can also think of
negative offsets as counting backward from the end.
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
Strings: sequence operations
Indexing (S[i]) fetches components at offset The first item
is at offset 0, S[0]. Negative indexes mean to count
backward from the end or right.
Slicing (S[i:j]) extracts contiguous sections of sequence
The upper bound is noninclusive.
Extended slicing (S[i:j:k]) accepts a step (or stride) k, which
defaults to +1. Allows for skipping items and reversing
order, S[::-1]
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
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
Note: The list is not exhaustive
capitalize ljust splitlines
upper rjust rsplit
lower split rstrip
count isdigit isspace
isalnum isidentifier find
isalpha islower isupper
isdecimal isnumeric 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
>>> 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
Lists are Python’s most flexible ordered collection object
type.
Unlike strings, lists can contain any sort of object:
numbers, strings, and even other lists.
Lists may be changed in place by assignment to offsets
and slices, list method calls, deletion statements, and
more, i.e., they are mutable objects.
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
Common list operations
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
Common list operations
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
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
Common list operations
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,)
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
Dictionaries
Dictionaries are one of the most flexible built-in data types
in Python.
If lists are ordered collections of objects, you can think of
dictionaries as unordered collections where items are
stored and fetched by key, instead of by positional offset.
Dictionaries also sometimes do the work of records or
structs
You can change dictionaries in place by assigning to
indexes (they are mutable), but they don’t support the
sequence operations that work on strings and lists.
Because dictionaries are unordered collections
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
Common dictionary operations
D={} # Empty dictionary
D={’name’: ’Bob’, ’age’: 40} # Two-item dictionary
E={’cto’:{’name’: ’Bob’,’age’:40}}# Nesting
D=dict(name=’Bob’,age=40) #Alternative construction
D=dict([(’name’, ’Bob’), (’age’, 40)])#keywords, key
D=dict(zip(keyslist, valueslist)) #zipped key/value
D=dict.fromkeys([’name’, ’age’])#key lists
D[’name’] # Indexing by key
E[’cto’][’age’] #
’age’ in D # Membership: key present test
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
Common dictionary operations
D.keys() # Methods: all keys,
D.values() # all values,
D.items() # all key+value tuples,
D.copy()# copy (top-level),
D.clear()# clear (remove all items),
D.update(D2)# merge by keys,
D.get(key)#fetch by key, if absent default (or None)
D.pop(key)#remove by key, if absent default (or erro
D.setdefault(key, default?)#fetch by key, if absent
D.popitem()#remove/return any (key, value) pair; etc
len(D)#Length: number of stored entries
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
Common dictionary operations
D[key]=42#Adding/changing keys
del D[key]#Deleting entries by key
list(D.keys())#Dictionary views (Python 3.X)
D1.keys() & D2.keys()#
D.viewkeys(), D.viewvalues()#Dictionary views
D = {x: x*2 for x in range(10)}#Dictionary comprehen
D = {chr(x+65): x**2 for x in range(6)}
D = {chr(i): i for i in range(65, 65 + 26)}
D = {chr(i): i for i in range(97, 97 + 26)}
L = [];
for i in range(65,91):L.append((chr(i),i));
D=dict(L)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
if...else statements
An else statement contains the block of code that executes if
the conditional expression in the if statement resolves to 0 or a
false value. The else statement is optional
if expression:
statement(s)
else:
statement(s)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
The Infinite Loop
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!"
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
for loop
for iterating_var in sequence:
statement(s)
Example:
for i in range(10):
if i%2==0:
print ’Number: ’, i
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Loop Control Statements
Loop control statements change execution from its normal
sequence.
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
The code block starts with a colon (:) and should be
indented.
The statement return [expression] exits a function,
optionally passing back an expression to the caller. A
return statement with no arguments is the same as return
None.
Syntax:
def functionname( parameters ):
"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
Calling a Function: You can execute it by calling it from
another function or directly from the Python prompt
Pass by reference vs value: All parameters (arguments) in
the Python language are passed by reference. It means if
you change what a parameter refers to within a function,
the change also reflects back in the calling function.
Inmutable objects act like "by-value": integer, float, long,
strings, tuples
Mutable objects act like "by-pointer": lists and dictionaries
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Avoiding mutable argument changes
To avoid mutable argument changes create a copy
Examples:
x = [1,2]; y = {0:’a’, 1: ’b’}
foo(x[:], y.copy() )
You can also create a copy inside the function
def foo(x,y):
xc = x[:] # for lists
yc = y.copy() # for dictionaries
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Avoiding mutable argument changes
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!!
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Function Arguments
Required arguments: Required arguments are the
arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should
match exactly with the function definition
Keyword arguments: When you use keyword arguments in
a function call, the caller identifies the arguments by the
parameter name: This allows us to place arguments out of
order.
Default arguments: It is an argument that assumes a
default value if a value is not provided in the function call
for that argument
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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
Variable-length arguments def func(**kwargs). kwargs is a
dictionary. It is similar to the previous *targs, but only
works for keywords arguments
>>> def func(**kwargs):
print kwargs
>>> func(x = 3, y = 4, z = 5)
>>> func(x = 3, 5) # Error !!!
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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}
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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!!
SyntaxError: non-keyword arg after keyword arg
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Anonymous function
>>> f = lambda x: [x, x**2, x**3]
>>> x = range(10)
>>> fx = map(f,x)
>>> fx
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
List Comprehension
>>> a = [ x for x in range(10)]
>>> b = [ x for x in range(10) if x%2==0]
>>> c = [[x,x**2,x**3] for x in range(10)]
>>> c = [[i*j for i in range(1,4)]
for j in range(1,5)]
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Modules
A module allows us to logically organize your Python code.
A module makes the code easier to understand and use.
A module is simply a file consisting of Python code, where
we can define functions, classes and variable
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Importing a module
Import Statement: One can use any Python source file as
a module by executing an import statement in some other
Python source file. The import has the following syntax:
import module1[, module2[,... moduleN]
from ... import Statement: We can import specific
attributes from a module
from modulename import name1[, ... nameN]]
from ... import * Statement: We can import all names from
a module into the current namespace
from modulename import *
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Importing a module. Example
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)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
The Module Search Path
Python’s module search path is composed of the concatenation
of the following components
The home directory of the program
PYTHONPATH directories (if set)
Standard library directories ( also from any .pth files (if
present))
The concatenation of these four components becomes sy path,
a mutable list of directory name string We can also add new
paths
>>> import sys
>>> sy path
>>> sy path.append(’yournewpath’)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
The dir( ) Function
The dir built-in function returns a sorted list of strings containing
the names defined by a module
>>> import math
>>> content = dir(math)
>>> print content
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
The reload Function
When the module is imported into a script, the code in the
top-level portion of a module is executed only once. Therefore,
if you want to reexecute the top-level code in a module, you can
use the reload function.
>>> reload(modulename)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Packages
A directory of Python code is said to be a package, so such
imports are known as package import
>>> import dir1.dir2.module as mm
>>> m myfunction
>>> from dir1.dir2.module import x
>>> print x
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Print
>>> a = int(raw_input(’numero: ’))
>>> print(’numero: ’, a)
>>> print(’numero: 0:4d 1:4d 2:4d 0:4.2f’.
format(a,a**2, a**3))
>>> print(’numero: 0:4d 1:10.2f ’.format(3,4))
>>> print("numero %.2f" % a)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Files-write
>>> f = open(’prueba.txt’, ’w’)
>>> f.write(’linea 1 \ n’)
>>> f.write(’linea 2 \ n’)
>>> f.write(’linea 3 \ n’)
>>> f.close()
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Files-read
>>> f = open(’prueba.txt’, ’r’)
>>> data = f.read()
>>> f.close()
>>> f = open(’prueba.txt’, ’r’)
>>> for line in f:
>>> print line
>>> f.close()
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Files-read
>>> f = open(’prueba.txt’, ’r’)
>>> print f.readline()
>>> print f.readline()
>>> f.close()
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Files-read
>>> f = open(’prueba.txt’, ’r’)
>>> lines = f.readlines()
>>> f.close()
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
main
Create the following file with name hola.py
def muestra_hola():
print("Hola")
if __name__ == "__main__":
muestra_hola()
$ python hola.py (in console)
In []:!python hola.py (in ipython)
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Package __init__.py file
There is one constraint you must follow: each directory named
within the path of a package import statement must contain a
file named __init__.py, or your package imports will fail
dir0\ # Container on module search path
dir1\
__init__.py
dir2\
__init__.py
module.py
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Overview of OOP Terminology
Class: A user-defined prototype for an object that defines a
set of attributes that characterize any object of the clas The
attributes are data members and methods, accessed via
dot notation.
Class variable: A variable that is shared by all instances of
a clas Class variables are defined within a class but
outside any of the class’s method
Inheritance : The transfer of the characteristics of a class
to other classes that are derived from it.
Instance: An individual object of a certain clas An object
obj that belongs to a class Circle, for example, is an
instance of the class Circle.
Instantiation : The creation of an instance of a clas
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Overview of OOP Terminology
Method : A special kind of function that is defined in a
class definition.
Object : A unique instance of a data structure that’s
defined by its clas An object comprises both data members
(class variables and instance variables) and method
Function overloading: The assignment of more than one
behavior to a particular function. The operation performed
varies by the types of objects (arguments) involved.
Operator overloading: The assignment of more than one
function to a particular operator.
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Creating Classes
class ClassName:
’Optional class documentation string’
classsuite
The class has a documentation string, which can be
accessed via ClassName.__doc__.
The classsuite consists of all the component statements
defining class members, data attributes and function
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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
Alternative attribute access:
The getattr(obj, name[, default]) : to access the attribute of
object.
The hasattr(obj,name) : to check if an attribute exists or
not.
The setattr(obj,name,value) : to set an attribute. If attribute
does not exist, then it would be created.
The delattr(obj, name) : to delete an attribute
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
Built-In Class Attribute
Alternative attribute access:
__dict__ : Dictionary containing the class’s namespace.
__doc__ : Class documentation string or None if
undefined.
__name__: Class name.
__module__: Module name in which the class is defined.
__bases__ : A possibly empty tuple containing the base
classes, in the order of their occurrence in the base class
list
See exampleInterfaseClasse py, ClassExample py: Classes
Employee and Point
Oscar Dalmau Python
Overview
Basic Syntax
Types and Operations
Statements and Functions
Modules
Input/Output
Classes and OOP
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
Overriding and Overloading methods
Overriding Methods: You can always override your parent
class method One reason for overriding parent’s methods
is because you may want special or different functionality
in your subclas
Oscar Dalmau Python