You are on page 1of 5

What is Python?

Some uses of Python


Python is: Things that Python is good at:
High-level System utilities
Python has hooks into standard OS-level services,
Artificial Intelligence Object-oriented
such as files, processes, pipes, etc.
Free, open-source
Programming Dynamically typed GUIs
Python has interfaces to Tk, Qt, and WxPython
Intro to Python Has a large collection of utility libraries
Embedded integration
garbage-collected
Chris Brooks Python has hooks that allow it to call/be called by C
Mixable - works nicely as a “glue” language and C++ code, and also COM interfaces.
Department of Computer Science Easy to learn/use Rapid Interactive Development
University of San Francisco
Like Lisp, Python makes it easy to quickly put
together a working program.
Scripting
Python has utilities for CGI, Database access,
Department of Computer Science — University of San Francisco – p.1/??
HTTP, Sockets, FTP, POP/SMTP, XML parsing, etc.
Department of Computer Science — University of San Fra

Invoking Python Programs Python Implementations Python Program Structure


There are four ways to run a Python program: /usr/bin/python on all unix machines and on OS X Programs consist of modules
Interactively IDLE and PythonWin on Windows A module corresponds to a source file.
From the command line MacPython on Macintosh Modules contain blocks of statements
As a script Statements create and process objects.
Also for Amiga, PalmOS, BeOS, etc.
From another program
BoaConstructor is an open-source Python IDE
Eclipse has a Python plugin (PyDev)

Department of Computer Science — University of San Francisco – p.3/?? Department of Computer Science — University of San Francisco – p.4/?? Department of Computer Science — University of San Fra
Basic Python Numbers Mathematical Operators
Python has a nice set of built-in data types Numbers work like we’d expect. Python has all the usual mathematical operators
Numbers There are integers, equivalent to longs in C. (1, -31311, +,=,*,/, %
Strings 4000) «, »
Lists There are long integers, which are of unlimited size ** or pow for exponentiation
Sets (31111L, 12345l)
abs, rand, |, &
Dictionaries There are floats, equivalent to doubles in C or Java.
Files 1.23, 3.1e+5 This makes Python a very handy desk calculator.
Using built-in types makes your code easier to There are Octal and Hexadecimal representations as in Operations are coerced to the most specific type.
write/maintain, more portable, and more efficient. C. (0155, 0x3af5) 3 + (4.0 / 2) will produce a float.
There are complex numbers, as in Lisp, Matlab, etc. Common error: since variables do not have declared
(3.0+4j) types, be careful of rounding: 3 /2 == 1 !!

Department of Computer Science — University of San Francisco – p.6/?? Department of Computer Science — University of San Francisco – p.7/?? Department of Computer Science — University of San Fra

Strings Strings Lists


One of Python’s strong suits is its ability to work with Strings are immutable sequences - to change them, we Python has a flexible and powerful list structure.
strings. need to make a copy. Lists are mutable sequences - can be changed in place.
Strings are denoted with double quotes, as in C, or Can’t do: s1[3] = ’c’
Denoted with square brackets. l1 = [1,2,3,4]
single quotes Must do: s2 = s1[0:2] + ’c’ + s1[3:]
Can create nested sublists. l2 = [1,2, [3,4, [5], 6], 7]
s1 + s2 - concatenation As in Java, making lots of copies can be very inefficient.
If you need to do lots of concatenation, use join instead. l1 + l2 - concatenation.
s1 * 3 - repetition
We’ll return to efficiency issues throughout the semester. l1 * 4 - repetition
s1[i] - indexing, s1[i:j] - slicing
l1[3:5], l1[:3], l1[5:] - slices
s1[-1] - last character
append, extend, sort, reverse built in.
“a % parrot” % “dead” - formatting
Range - create a list of integers
for char in s1 - iteration

Department of Computer Science — University of San Francisco – p.9/?? Department of Computer Science — University of San Francisco – p.10/?? Department of Computer Science — University of San Fran
Dictionaries Tuples Files
A Dictionary is a Python hash table (or associative list) Tuples are like immutable lists. Since it’s a scripting language, Python has a lot of
Unordered collections of arbitrary objects. Nice for dealing with enumerated types. support for file I/O
d1 = {} - new hashtable d2 = {’spam’ : 2, ’eggs’, 3} Can be nested and indexed. Operators are not too different from C.
Can index by key: d2[’spam’] t1 = (1,2,3), t2 = (1,2,(3,4,5)) Outfile = file(’fname’, ’w’) or infile = file(’fname’, ’r’)
’r’ is default and can be left out
Keys can be any immutable object. Can index, slice, length, just like lists.
t1[3], t1[1:2], t1[-2] S = infile.read() - read the entire file into the string S.
Can have nested Hashtables
d3 = {’spam’ : 1, ’other’ :{’eggs’ :2, ’spam’ : 3}} Tuples are mostly useful when you want to have a list of S = infile.read(N) - read N lines into the string S.
d3[’other’][’spam’] a predetermined size/length. S = input.readline() - read one line
has_key, keys(), values(), for k in keys() Also, constant-time access to elements. (fixed memory S = input.readlines() - read the whole file into a list of
locations) strings.
Typically, you’ll insert/delete with:
Tuples are also very useful as keys for dictionaries. Unless the file is really huge, it’s fastest to read it all
d3[’spam’] = ’delicious!’
in at once with read() or readlines()
del d3[’spam’]
Department of Computer Science — University of San Francisco – p.12/?? Department of Computer Science — University of San Francisco – p.13/?? Department of Computer Science — University of San Fran

Files Basic Python statements Python variables


outfile.write(S) - write the string S into the file. Python uses dynamic typing. Variables must:
outfile.writelines(L) - write the list of strings L into the file. No need to pre-define variables. begin with a letter or underscore
outfile.close() (this is also done by the garbage collector) Variables are instantiated by assigning values to them contain any number of letters, numbers, or
Referencing a variable before assignment is an error underscores.
You can assign multiple variables simultaneously No $, @, #, etc.
spam = 4 Case matters.
eggs = 5
spam, eggs = eggs, spam
Can’t use reserved words as variables.
spam, eggs = 4,5

Department of Computer Science — University of San Francisco – p.15/?? Department of Computer Science — University of San Francisco – p.16/?? Department of Computer Science — University of San Fran
Printing Conditionals Conditionals
We’ve already seen the basic print. The general format for an if statement is: Logical tests return 1 for true and 0 for false.
print “hello world” if <test1> : “True” and “False” are shorthand
<statement1>
To use a formatting string, do: <statement2> and, or, not are available for compound tests
print “hello %s” % “bob” elif: <test2> :
<statement3>
print "%s %s" % ("hello" , "world") else:
<statementn>
To suppress the linefeed, include a ,
Notice the colons after the conditionals.
Compound statements consist of the colon, followed by
an indented block.

Department of Computer Science — University of San Francisco – p.18/?? Department of Computer Science — University of San Francisco – p.19/?? Department of Computer Science — University of San Fran

Syntax Iteration For


Indentation is used to delimit blocks Python has the familiar while loop. For is a generic iterator in Python.
(If you are going to be editing your code on multiple One wrinkle: it has an optional else clause to execute if Lets you loop over any indexable data structure.
machines with different editors, you may want to the test is false. for item in [1,2,3,4,5]
configure your editor to use spaces instead of tabs.)
Additional loop control for char in “This is a string”
Statements can cross multiple lines if:
break for key in dictionary
They’re within delimiters
Exit the innermost loop without doing an else This provides a uniform (polymorphic) interface to a set
You use a backslash
continue of different data structures.
Return to the beginning of the loop
Note: it’s much faster to use the polymorphic operator
pass than to access manually.
Do nothing
i.e. for item in list is faster than for i in len(list)
for item in dictionary is faster than for item in
dictionary.keys()

Department of Computer Science — University of San Francisco – p.21/?? Department of Computer Science — University of San Francisco – p.22/?? Department of Computer Science — University of San Fran
Functions Functions Basic Python advice
def is used to define a function. Multiple values can be returned in a tuple. Let the language do the work for you
return returns a value We can also provide default arguments. e.g.: if x in [1,2,3,4] rather than an an explicit loop
Functions maintain local scope Functions can be called with keywords. this is both faster and more readable
Names are resolved locally, then globally, then built-in myfunc(spam=1, eggs=2) Use a Python-aware editor/IDE
*args can be used to catch arbitrary argument lists and Take advantage of the built-in modules whenever
store them in a tuple. possible.
**args can be used to catch arbitrary argument lists and Use the interpreter to help test your code
store them in a dictionary. All built-in modules are readable
Looking at these can give insights into how they
work, as well as how to write good Python code.

Department of Computer Science — University of San Francisco – p.24/?? Department of Computer Science — University of San Francisco – p.25/?? Department of Computer Science — University of San Fran

You might also like