Python Tutorial

foremanyellowSoftware and s/w Development

Nov 7, 2013 (3 years and 7 months ago)

62 views

MSE 237
What is Python?

Programming Language

Easy to setup and use

Best for short simple programs

Everything is done when program runs

No compilation
Setting Up Python

Go to
http://www.python.org/

Download python 2.6.5

Set Environment Path

For Vista: Go to

Control Panel

System (may have to switch to classic view)

Advanced System Settings (on the left side)

Environmental Variables

Under System Variables, there should be an entry named
Path
Setup Continued

Click Edit

Add semicolon (;) + directory you installed python to under
variable values

C:
\
Python26 is the default installation directory

It should look like <old stuff>;C:
\
Python26
Test for successful installation

Open Command Prompt (under Accessories)

Or type
cmd
in the search bar that appears when you
press Start

Type python
Path not set
correctly
Path set
correctly
Installing JSON

Go to
http://pypi.python.org/pypi/simplejson

Download
simplejson
-
2.1.1.tar.gz

Unzip it

Go to where you unzipped it

Type python setup.py build

Once that completes python setup.py install

Testing

Type import simple
json
in the interpreter
Other useful packages

http://pypi.python.org/pypi/DeliciousAPI/1.6.3
Coding in python

Use the Interpreter!

Accessed by typing in python with no arguments

Test your code and understand how it works

Syntax is very different from C/C++/Java
Sample Python Program
Syntax explanation

When you run a python program, it goes from top to
bottom and executes the code given

The file you run will have __name__ = __main__

Hence the last 2 lines on the file

Optional but makes things cleaner

def is a definition of a function

Format def <
functionName
>(arg0, arg1,…):

Colon (:) denotes the start of a block

Comparable to { in other languages
Syntax Continued

No semicolon (;) to denote end of line

Use indentation (aka spacebar) to separate blocks of
code

Do not use TAB (it sometimes messes up the program)

Comment using #

Use print liberally to check status of variables
Sample Python Program
Variables

No type declaration

Simply name them and assign them a value

Can be re
-
assigned as you wish

Name them properly so you remember what they are
used for
Strings

Define using single quotes ‘like this’

Double “quotes” works too (usually)

Strings can be thought of as Lists of characters

Lists to be covered later

No char data type

Access individual chars through string[index]

Useful operators

+ concatenates 2 strings together

s
tr
(
var
) (converts other data type (usually number) to string

Use u for
unicode
string

String =
u‘hello

Lists

Python’s version of arrays

Defined using []

Indexes start from 0

Negative indexes count from the back

Each element
does not have to be the same type

But try to make it so as its much easier to work with

Useful operators

+ add 2 lists together

Slicing [: n] (cut list up according to index n)
L
ists

Useful operators

+ add 2 lists
together

sorted(
listName
)

sorts the list

Slicing [: n] (cut list up according to index n
)

range (Number)

Creates a list starting from 0 to Number
-
1

<
elem
> in <list>

Returns True if
elem
is in list
Sample Code
Conditional Statements

if <condition> :

No need for () around the condition

Boolean operators are and, or, not (yes, just type the
word)

== works as per normal

else is the same, but else
-
if is written
elif
L
oops

for <
varName
> in <
listName
> :

Similar to a
foreach
loop in Java

Try to use this if possible

for
i
in range(Num)

Traditional
for
-
loop (from 0 to Num
-
1)

while <
boolean
condition> :

Traditional while
-
loop
Custom Sorting

Python can sort a list according to a custom definition
you provide

sorted(
listName
, key=
keyFn
)

keyFn
takes in one element of the list and returns a
number

List is sorted in ascending order based on the returned
number

def
keyFn
(s):
return
val
#some value that depends on s
Sorting

Traditional 2 variable sorting is also possible

sorted(
listName
,
cmp
=
cmpFn
)

def
cmpFn
(a, b):
return
val
#some value that depends on
a and b

To sort
in reverse order add in
reverse=True

sorted(
listName
,
key=
keyFn
, reverse=True)
Sort Example
Dictionary

Stores key
-
value pairs

Defined using {}

Keys usually either a string or a number

Value can be anything

To put something in

Dict
[‘
myKey
’] = my
Value

Dict
[‘
myKey
’] = my
Value2 will replace the old value with new
one

To retrieve

RetrievedValue
=
Dict
[‘
myKey
’]
Dictionary

Use ‘in’ to make sure a key is in the dictionary before
attempting to retrieve a value

Useful functions

Dict.keys
()

Dict.values
()

Returns a list of the keys and values respectively
Project

The delicious JSON feed returns a lists of dictionaries

Format
Key
Value
‘a’
User
name
‘d’
Title of page
‘u’
URL of
page
‘t’
Tags
used on page
(is a list of strings)

dt

Date Tagged
Useful Links

http://code.google.com/edu/languages/google
-
python
-
class/

Very good site for python

Written by Nick
Parlante
who teaches it here at Stanford

The section on
tuples
(under Sorting might be useful)