Title: Introduction to
1 2What is Python?
- Dynamic, interpreted high-level language.
- Created in 1991 by Guido van Rossum.
- Design philosophy Short development time is
prioritized over excecution speed. - Syntax similar to C or Java.
3Facts about Python
- Portable, available for all common platforms.
- Python is Open Source and free to use, even for
commercial applications. - (Relatively) Easy to integrate with other
languages, such as Java, C/C, Fortran and .NET. - Designed for multiple paradigms. Both object
oriented and procedural programming are possible.
4What is Python good for?
- Internet applications, good support for HTTP,
FTP, SMTP and CGI. - Integrating components written in a low-level
language, glue code. - Portable system tools, same commands on each
platform. Compare with dir (Windows) and ls
(Linux). - Portable GUIs.
- Database handling.
- Projects where time of development is more
important than speed of execution.
5What is Python not good for?
- Tasks where performance is critical.
- Such tasks can be implemented in C/C modules
using tools such as SWIG (www.swig.org).
6Python and VTK
- VTK is written in C, but has bindings to
Python, Java, Tcl ... - For this workshop, we will use VTK with Python.
7The Python prompt
- Can be used to execute individual Python commands
interactively. - The prompt has a memory which is kept until the
prompt is closed. - Start the prompt by typing python in a terminal.
8The Python language
- Variables and types
- Control structures
- Functions
- Classes
- File handling
9Variables
- All variables in Python are references
Variable
Data
10Variable names
- May contain english letters, numbers and
underscores. - Must not start with a number.
Invalid names
Valid names
påskmust 1_varname varname 1 varname
varname vArNaMe1 var_name_1 _var_name
11Variable assignment
a 10 b 20 c a b
- A reference is created with
Creates the following situation
a
10
b
20
c
30
12More on references
- Multiple references Many variables can refer to
the same object. - Reference counting An object is deleted
automatically when no variables refer to it.
gtgtgt list 1, 2, 3 gtgtgt list_a 1, 2, 3 gtgtgt
list_b list_a gtgtgt list_c list_b gtgtgt list_c2
78 gtgtgt list_a 1, 2, 78
list_a
1, 2, 3
list_b
list_c
13Datatypes
- Numbers
- Strings
- Boolean types
- Lists
- Tuples
- Others...
14Numbers
gtgtgt a 10 gtgtgt a.__class__ lttype 'int'gt gtgtgt
big_num 9875628736L gtgtgt big_num.__class__ lttype
'long'gt gtgtgt pi_constant 3.1415 gtgtgt
pi_constant.__class__ lttype 'float'gt gtgtgt z
complex(3.4, 8.35)? gtgtgt z (3.3999999998.349999999
j)? gtgtgt z.__class__ lttype 'complex'gt
- Different kinds of numbers are represented by
different classes - Integers (int)?
- Big integers (long)?
- Real numbers (float)?
- Complex numbers (complex)?
15Operations on numbers
- The operations , -, and / work as usual.
- - Remainder
- // - Integer division
- - Power
- abs(x)?
- int(x)?
- long(x)?
- float(x)?
- complex(a, b)?
gtgtgt a 3.14 gtgtgt b 5 gtgtgt c b / a gtgtgt
c.__class__ lttype 'float'gt gtgtgt 5 // 2 2 gtgtgt 5 //
float(2)? 2.0 gtgtgt 5 / float(2)? 2.5 gtgtgt b /
complex(6, 4)? (0.576923072-0.384615381j)? gtgtgt 2
/ 3 0
16Strings
- A string is a sequence of characters.
- A string is created using single or double quotes.
gtgtgt s1 "exempeltext" gtgtgt s2 'exempeltext
igen' gtgtgt s3 "felaktigt' File "ltstdingt", line
1 s3 "felaktigt' SyntaxError EOL
while scanning single-quoted string gtgtgt s4 s1
s2 gtgtgt s4 'exempeltextexempeltext igen' gtgtgt s5
str(3)? gtgtgt s5 '3' gtgtgt s5.__class__ lttype 'str'gt
17Boolean types
- The following expressions are false
- None
- False
- The number 0
- Every empty sequence
- Every empty mapping
- All other objects are (somewhat simplified)?
defined to be true.
gtgtgt a True gtgtgt a.__class__ lttype 'bool'gt gtgtgt a
5 gt 7 gtgtgt a False
18Lists
- Lists are containers with an arbitrary number of
elements. - The elements can be any Python object. A single
list can contain objects of many different types.
gtgtgt list 1, 2, 3 gtgtgt list 1, 2, 3 gtgtgt
list_2 1, "mixed", "li""st" gtgtgt list_2 1,
'mixed', 'list'
19More on lists
- Individual element are accessed with an index
within square brackets index. The first element
has index 0.
gtgtgt list_2 1, 'blandad', 'lista' gtgtgt
list_21 'blandad' gtgtgt list_21 "Nytt
element" gtgtgt list_2 1, 'Nytt element', 'lista'
20Tuples
- Tuples are static lists.
- Tuples have better performance than lists, but
are less flexible.
gtgtgt tuple_1 (1, 2, 3)? gtgtgt tuple_2 (1,
"mixed")? gtgtgt tuple_21 'mixed' gtgtgt tuple_21
"New element" Traceback (most recent call
last) File "ltstdingt", line 1, in
ltmodulegt TypeError 'tuple' object does not
support item assignment
21Printing
- The Python command for writing text to the prompt
is print.
gtgtgt print "Hello" Hello gtgtgt print "Hello",
"world" Hello world gtgtgt print 103 13
22If-statements
- Note the indentation! In Python, indentation is
used to control which block a statement belongs
to. A colon indicates that a new block of code
begins.
gtgtgt a 10 gtgtgt if a gt 5 ... print "The number
is greater than 5" ... The number is greater than
5
23else
gtgtgt a 10 gtgtgt if a lt 5 ... print "a is less
than 5" ... else ... print "a is greater than
or equal to 5" ... a is greater than or equal to 5
24Multiple choices
- Multiple choices are handled with elif.
- Many languages have a case-statement for handling
multiple choices. This was deemed redundant by
the Python developers.
gtgtgt a 10 gtgtgt if a 1 ... print "a is
one" ... elif a 2 ... print "a is two" ...
elif a 3 ... print "a is three" ...
else ... print "a is something else" ... a is
something else
25for-loops
- Again, use indentation to define a block of code.
gtgtgt for i in range(10) ... print
i ... 0 1 2 3 4 5 6 7 8 9
26Nested loops
gtgtgt for i in range(2) ... for j in
range(3) ... for k in range(4) ... print
"ii, ji, ki" (i, j, k)? ... i0, j0,
k0 i0, j0, k1 i0, j0, k2 i0, j0,
k3 i0, j1, k0 i0, j1, k1 ... i1, j1,
k2 i1, j1, k3 i1, j2, k0 i1, j2,
k1 i1, j2, k2 i1, j2, k3
27Beyond the Python prompt
- The python prompt is not suited for larger
programs. - Python programs are stored in regular text files.
- Commonly the filenames end with .py, but this is
not required.
28Executing Python programs
- Python files are executed using the python
command. - The search path to this program must be set.
- On windows, this is set by the system variable
PYTHONPATH.
29 Python is dynamically typed
-- coding utf-8 -- a refers to a number a
10 print a, a.__class__ a refers to a
string a "lkshjdglgv" print a, a.__class__ a
refers to a list a 5, 2, 8, 5 print a,
a.__class__ a.sort()? a refers to a number
again a 10 a.sort()?
gt python dynamic_binding.py 10 lttype
'int'gt lkshjdglgv lttype 'str'gt 5, 2, 8, 5 lttype
'list'gt Traceback (most recent call last) File
"dynamic_binding.py", line 18, in ltmodulegt a.sort(
)? AttributeError 'int' object has no attribute
'sort'
Duck Typing "when I see a bird that walks like
a duck and swims like a duck and quacks like a
duck, I call that bird a duck."
30 Python is strongly typed
- No implicit type conversions
gtgtgt a 3 gtgtgt b '4' gtgtgt a b Traceback (most
recent call last) File "ltstdingt", line 1, in
ltmodulegt TypeError unsupported operand
type(s)? for 'int' and 'str' gtgtgt str(a)
b '34' gtgtgt a int(b)? 7
31Functions in Python
- A function is create using the reserved word def
followed by the function name and a colon. - The rules for function names are the same as for
variable names.
function_01.py def function_a() print "Detta
skrivs inuti funktionen." print "Detta skrivs
först." function_a() Funktionen anropas print
"Detta skrivs efter metodanropet."
gt python function_01.py Detta skrivs
först. Detta skrivs inuti funktionen. Detta
skrivs efter metodanropet.
32Function arguments
- We communicate with functions by specifying
arguments in the function call.
function_02.py def greeting(name, age) print
"""Hej s. Du är i år gammal.""" (name,
age)? greeting("Maja", 23)? greeting("Pelle",
31)?
gt python function_02.py Hej Maja. Du är 23 år
gammal. Hej Pelle. Du är 31 år gammal.
33Default arguments
- Default arguments can be used to avoid having to
specify all arguments.
function_03.py def greeting(name,
age20) print """Hej s. Du är i år gammal."""
(name, age)? greeting("Maja",
23)? greeting("Pelle")?
gt python function_03.py Hej Maja. Du är 23 år
gammal. Hej Pelle. Du är 20 år gammal.
34Order of arguments
- Problems with many arguments Arguments must be
given in the order given in the function
defintion.
function_04.py def greeting(name"Unknown",
age20) print """Hello s. You are i years
old.""" (name, age)? greeting()? greeting("Pell
e")? greeting(45) Gives the wrong result
gt python function_04.py Hello Unknown. You are
20 years old. Hello Pelle. You are 20 years
old. Hello 45. You are 20 years old.
35Arguments by name
- The solution is to give arguments by name.
function_05.py def greeting(name"Okänd",
age20) print """Hej s. Du är i år gammal."""
(name, age)? greeting()? greeting("Pelle")
Still works greeting(name"Pelle")
Eqvivalent greeting(age45) Gives the right
result greeting("Maja", 33)? greeting(name
"Maja", age 33) Eqvivalent
gt python function_05.py Hej Okänd. Du är 20 år
gammal. Hej Pelle. Du är 20 år gammal. Hej Pelle.
Du är 20 år gammal. Hej Okänd. Du är 45 år
gammal. Hej Maja. Du är 33 år gammal. Hej Maja.
Du är 33 år gammal.
36Return values
- The return statement is used to return a value
from a function.
return_values_01.py def my_own_join(texts,
separator" ") s "" for text in texts s
text separator s s-len(separator)
"." return s my_text_pieces "Detta", "är",
"inte", "så", "meningsfullt" print
my_own_join(my_text_pieces, "_")?
gt python return_values_01.py Detta_är_inte_så_men
ingsfullt.
37Multiple return values
- Python allows any number of return values.
return_values_03.py def min_max(seq) return
min(seq), max(seq)? a 3, 573, 234,
24 minimum, maximum min_max(a)? print minimum,
maximum result min_max(a)? print result print
result.__class__
gt python return_values_03.py 3 573 (3,
573)? lttype 'tuple'gt
38Modules
- When writing larger programs, it is not practical
to keep all code in the same file. - In python Modules offer a way to separate large
programs into smaller units. - Modules are also used to organize functions and
variables into namespaces.
39Standard modules
- Python has a number of standard modules that are
always available for import. - Modules are imported with the import-statement.
gtgtgt sys Traceback (most recent call last) File
"ltstdingt", line 1, in ltmodulegt NameError name
'sys' is not defined gtgtgt import sys gtgtgt
sys ltmodule 'sys' (built-in)gt gtgtgt
sys.version '2.4.3 (1, Dec 11 2006, 113903)
\nGCC 4.1.1 20061130 (Red Hat 4.1.1-43)'
403rd party modules
- Lots of freely available modules for
- GUIs
- Image Processing
- Computer Graphics
- Web development
- Numerical Computations
- ...
41Object oriented programming
- Python is originally a procedural language, with
added support for object orientation. - Classes are defined using the class keyword
-- coding utf-8 -- io_01.py class
MyClass MyNumer10 def printNumber(self) prin
t 'The number is ',MyNumber Now we use the
class anObjectMyClass()? anObject.printNumber()?
42Object oriented programming
- Python is originally a procedural language, with
added support for object orientation. - Classes are defined using the class keyword
-- coding utf-8 -- io_01.py class
MyClass MyNumer10 def printNumber(self) pri
nt 'The number is ',MyNumber Now we use the
class anObjectMyClass()? anObject.printNumber()?
43Private variables
- Python has limited support for private class
variables. - Variable names starting with two underscores
(__) are considered private. - If you really want to, it is still possible to
access those variables from outside the class.
44File I/O in python
- Files are opened with the open statement
-- coding utf-8 -- io_01.py f
open("newfile.txt", "r") Öppna filen print
f.read() Läs in hela filen
r -read only w- write only r - read and
write a - append data at the end of the
file b- binary file
45Reading parts of a file
-- coding utf-8 -- io_01.py f
open("newfile.txt")? for row in
f.readlines() print row, f.close()? f
open("newfile.txt")? print f.read(8)? print
f.read(5)?
gt python io_02.py Detta är textrad 1. Detta är
textrad 2. Detta är textrad 3. Detta är textrad
4. Detta är text
46Writing to a file
-- coding utf-8 -- io_03.py f
open("newfile.txt", "w")? f.write(str(3)
"\n")? f.write(str(1,2,3) "\n")? f.write(str(
"name""Kalle") "\n")? f.close()? f
open("newfile.txt", "a")? f.write("Denna rad
läggs till.")? f.close()? f open("newfile.txt")
? print f.read()? f.close()?
gt python io_03.py 3 1, 2, 3 'name'
'Kalle' Denna rad läggs till.
47That's it!
- Now you know the basics
- More info www.python.org