introduction to python programming introduction to python programming python is a versatile language...

14
1 Introduction to Python Programming Python is a versatile language used for many applications at Space Telescope Science Institute. For application programs, test automation, operational procedures and scientific analysis, Python is in current use here. Emphasizing the fundamentals of the Python Programming language this course is taught from the bottom up for the beginning programmer to the professional. What you will learn … Assignment, operators, and methods of Python Data Types File, command line, and parameter handling Decision and flow control Python object oriented concepts and implementations, using and creating your own class objects How to use Python’s standard library of modules and how to create and use your own How to develop a GUI to initiate your own program For program details, please visit: http://www.stsci.edu/hst/training Auditorium 11:30am - 1pm Questions? Contact [email protected] or [email protected] Jim Hare Mondays - March 3, 10, 24, 31, April 7, 14. STSCI Python Introduction An introduction to the language. Jim Hare

Upload: dangque

Post on 29-Jun-2018

240 views

Category:

Documents


0 download

TRANSCRIPT

1

Introduction to Python Programming

Python is a versatile language used for many applications at Space Telescope ScienceInstitute. For application programs, test automation, operational procedures andscientific analysis, Python is in current use here. Emphasizing the fundamentals of thePython Programming language this course is taught from the bottom up for thebeginning programmer to the professional.

What you will learn …• Assignment, operators, and methods of Python Data Types• File, command line, and parameter handling• Decision and flow control• Python object oriented concepts and implementations, using and creating your own class objects• How to use Python’s standard library of modules and how to create and use your own• How to develop a GUI to initiate your own program

For program details, please visit: http://www.stsci.edu/hst/training

Auditorium 11:30am - 1pm

Questions? Contact [email protected] or [email protected]

Jim Hare

Mondays - March 3, 10, 24, 31, April 7, 14.

STSCI Python Introduction

An introduction to the language.

Jim Hare

2

Why Teach you Python?

• Object-Oriented – Easiest language I haveever programmed.

• Reuse of tools.

• Freedom from mechanical or manualprocedures.

• Used for development, operationsprocedures, and test scripting.

Class 1 Agenda

• Your Python setup

• Executing a file

• Data Types

3

Your Python Setup

• PYTHONPATH environment variable:– setenv PYTHONPATH \

“/ess5/psdpython/:/ess5/sit/planning/commands/:/usr/local/STPYTHON/:”

• >python # Interactive python session

Executing a File• Header template files are available – download

from my page header_template.py• Executing a file

– From Unix >python exmod1.py– If file’s first line has #!usr/local/bin/python >exmod1.py– From python >>execfile(‘exmod1.py’) or

execfile(‘/ess5/psdpython/pythonclass/class1/exmod1.py’)

– import exmod1 # Only once!– reload(exmod1) # Second time!

4

print and raw_input

• >>> x = 2

>>> print x

2

>>> day = raw_input(“What day is it?”)

What day is it?

Monday

>>> print “Today is “, day

Today is Monday

Data Types -Numeric

• There are four built-in numeric types:– integers I = 10 or I = int(’10’)– long integers I = long(’10’) or I = 10L– Floating-point numbers x = 3.1415926 or

x = float(“3.1415926”)– Complex numbers c = 1.2 + 12.34J

• See p14 in reference “Python EssentialReference”

5

Strings

• a = ‘helloWorld’ or a = “helloWorld” ora = “””helloWorld”””

a[0] is ‘h’ a[9] or a[-1] is ‘d’ a[0:5] is ‘hello’

a[:5] is “hello” a[5:] is “World”

-1-2-3-4-5-6-7-8-9-10

9876543210

dlroWolleh

Lists and Tuples• names = [“Jim”, “Jeff”,”Jayne”,”Joyce”]• Junk =

[1,”Dave”,3.14,[“Mark”,7,9,[100,101],0]A = [1,2,3]Caution: List1 = List2, List1 has a reference to

List2 Use List1 = copy.deepcopy(List2) to copyby value Example: exdatatype1.py

Page 24, Table 3.4 List Methods

• Tuples – tuple1 = (1,3,25,3.4) tup2 = (3,)

6

Sequence Operations andMethods

• Sequences – strings, lists, tuples

• s[i] Returns element i of sequence s

• s[i:j] Returns elements i up to j of s

• len(s) Number of elements in s

• min(s) Minimum value in s

• max(s) Maximum value in s

List Methods

• list(s) – converts s to a list

• s.append(x) – appends element x to s

• s.extend(t) – appends list t to the end of s

• s.count(x) – count of occurrences of x in s

• s.index(x) – returns smallest i, s[i] == x

• s.insert(i,x) – Inserts x at index i

• s.pop([i]) – returns element i and remove from thelist. If i omitted, the last element is returned.

7

List Methods - continued

• s.remove(x) – Search for x and remove it.

• s.reverse() – reverses items of s in place

• s.sort([cmpfunc]) – sorts items in place.cmpfunc is a comparison function

String Methods

• S.capitalize() – capitalizes the first character

• S.center(width) – centers string in width

• S.count(sub [,start [, end]]) – countsoccurrences of sub string

• S.endswith(suffix [, start [,end]]) –check forsuffix

• S.expandtabs([tabsize]) – expand tabs

8

String Methods - continued

• S.find(sub [,start [,end]]) – finds first sub

• S.index(sub [,start [,end]]) – finds first subor raises exception

• S.isalnum() – checks that all alphanumeric

• S.isalpha() – checks all alphabetic

• S.isdigit() – checks all are digits

• S.islower() – checks all lowercase

String Methods - continued

• S.isspace() – checks all whitespace

• S.istitle() – checks the string is title-cased

(first letter of word capitalized)

• S.isupper() – checks all uppercase

• S.join(t) – joins strings in list t using s asdelimiter

• S.ljust(width) – left justifies string in width

9

String Methods - continued

• S.lower() – converts to lowercase

• S.lstrip() – strips leading whitespace

• S.replace(old, new[,maxreplace]) – replacesold with new substring

• S.rfind(sub [,start[,end]]) – find last sub

• S.rindex(sub [,start[,end]]) – find last sub orraise exception

String Methods - continued

• S.rjust(width) – right-align s in width• S.rstrip() – remove trailing whitespace• S.split([sep [,maxsplit]]) – splits a string

using sep as delimiter. Maxsplit is themaximum number of splits to perform.

• S.splitlines([keepends]) – splits a string intoa list of lines, if keepends is 1, trailingnewlines are preserved

10

String Methods - continued

• S.startswith(prefix [,start[,end]]) – Checks if stringstarts with prefix

• S.strip() – removes leading and trailing whitespace

• S.swapcase() – swaps lower and upper case

• S.title() – title cases string

• S.translate(table [,deletechars]) – translates astring using a character translation table

• S.upper() – returns S converted to uppercase

Dictionaries

DictionariesDictionary1 = {}

Draft = {‘player’:‘Jason Williams’, ‘pick’: 2,‘team’:’Bucks’,’school’: ‘Duke’}

Draft2 = [{‘player’:‘Jason Williams’, ‘pick’: 2,‘team’:’Bucks’,’school’: ‘Duke’},{‘player’:’Juan Dixon’,’pick’:17,‘team’:’Wizards’, ’school’:’Maryland’}]

11

Dictionary – Index is the Key

• Draft = {} # This has to be declared first

• Draft[‘player’] = ‘Lonnie Baxter’

• Draft[‘pick’] = ’44’

• Draft[‘team’] = ‘Bulls’

• Draft[‘school’] = ‘Maryland’

Dictionary Tree

• Tree = {'Roger Hare':{'children':{'Jim Hare':{'children':{'Zach Hare':

{'children':{}},'Devan Hare':{'children':{}}}}, 'Jeff Hare': {'children':{'Justin Hare': {'children':{}},'Bendan Hare':{'children':{}}, 'Ryan Hare':{'children':{}}}}, 'Jayne Hare':{'children':{}}, 'Joyce Hare':{'children':{}}}}}

12

Dictionary Methods

• len(m) – returns number of items in m

• m[k] – returns the item of m with the key k

• m[k] = x – sets m[k] to x

• del m[k] – removes m[k] from m

• m.clear() – removes all items from m

• m.copy() – returns a copy of m

• m.has_key(k) – returns 1 if m has key k, or 0

Dictionary Methods - continued• m.items() – returns a list of (key,value) pairs.• m.keys() – returns a list of key values• m.update(b) – adds all objects from dictionary b to

m• m.values() – returns a list of all values in m• m.get(k[,v]) – returns m[k] if found; otherwise

returns v• m.setdefault(k[,v]) – returns m[k] if found;

otherwise returns v and sets m[k] = v• m.popitem() – removes a random (key,value) pair

from m and returns it as a tuple

13

Homework

• Write a program demonstrating the use of asmany of the string methods as you can andprint results.

• Make the program interactive by usingraw_input command to ask for someinformation to print.

Class 2

• Formatting to strings

• Passing arguments to Modules

• Functions

• Looping and Control

14

References

• Python Essential Reference, Second Edition,David M. Beazley, New Riders,2001

• www.python.org