Transcript PythonIntro
CSC1018F:
Programming with Python
James Gain
[email protected]
Donald Cook
[email protected]
A Brief History of Python
Created by Guido van Rossum (a
Monty Python’s Flying Circus
enthusiast) in the early 1990’s
Intellectual property now owned by
the Python Software Foundation (PSF)
Not a toy language. Used by:
Industrial Light and Magic on the Star
Wars movies
NASA for their engineering repository
Characteristics of Python
Interpreted, interactive, object-oriented
programming language
Powerful
Batteries included (300+ libraries)
Well supported
OpenSource but copyrighted
Portable because it exploits the underlying ‘c’ installation
on most systems
Easy to learn
Borrows proven concepts from other languages
Less scaffolding required
Zen of Python: “simple is better” or “principle of least
astonishment”
Hello World
Java:
C++:
Python:
// Hello World in Java
class HelloWorld {
static public void main(String args[]) {
System.out.println(“Hello World!”);
}
}
// Hello World in C++
#include <iostream.h>
Main() {
cout << “Hello World!” << endl;
return 0;
}
# Hello World in Python
print ‘Hello World!’
Course Structure
Lectures:
4th period Mondays (Overview of Section) and
Fridays (Mini-test and Tutorial)
Afternoon Tutorial
2 hours on Monday or Tuesday
Textbook
Mark Pilgrim, “Dive into Python”
http://diveintopython.org
Self Study
1.5-2 hours work per day
Do not merely read the textbook
Syllabus
Week 1
Introduction to Python
DIP Ch 2-3
Week 2
Intermediate Python
DIP Ch 4
Week 3
DIP Ch 5
Week 4
Objects and Object
Orientation
Advanced Python
Week 5
Functional Programming
DIP Ch 16
Week 6
Visual Python
-
Remain- Software Engineering &
Battleship Project
der
DIP Ch 6 - 7
DIP Ch 1315
Diving In
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)
Declaring Functions:
def keyword, no return data type defined, arguments (with
no pre-defined type) which are comma separated
Comparing Python Datatypes
Languages can be classified as:
Statically typed - types are fixed by declaration
at compile time
Dynamically typed - types are discovered at
execution time
Strongly typed - types are enforced and cannot
be interchanged without conversion
Weakly typed - types are freely ignored, no
explicit conversion is necessary
Python is dynamically and strongly typed
Documenting Functions
Triple quotes (" " ") signify a multi-line
comment
Allows you to create a string containing
single and double quotes
Often used to define a doc string
First thing defined in a function
Available at run-time as an attribute of
the function
function.__doc__
Indenting Code
Blocks of code are defined by indentation
Indenting starts a block and unindenting ends it
No need for explicit braces, brackets or keywords
Whitespace is significant
Code blocks are started by a ‘:’
def fib(n):
print 'n =', n
if n > 1:
return n * fib(n - 1)
else:
print 'end of the line'
return 1
Dictionaries
eng2fr = {"one":"un", "two":"deux",
"three":"trois"}
An unordered set consisting of key-element pairs
Retrieval:
You can get keys (e.g., eng2fr["one"]) by value
But not values by key (e.g., eng2fr["un"])
No duplicate keys
Assigning values to an existing key will overwrite it
Dictionary keys are case-sensitive
Power!
Values can mix and match any datatypes (even other
dictionaries)
Keys can combine immutable datatypes
Operating on Dictionaries
Modifying a dictionary
>>> eng2fr["four"] = "quatre"
>>> eng2fr
{"one":"un", "two":"deux", "three":"trois",
"four":"quatre"}
Deleting Items
>>> del eng2fr["one"]
>>> eng2fr
{"two":"deux", "three":"trois","four":"quatre"}
>>> eng2fr.clear()
>>> eng2fr
{ }
Lists
Horsemen = ["war", "famine",
"pestilence", "death"]
The Python Workhorse
Much more than a java array
Can grow dynamically
Can include datatypes of any element
Indexed by element number
Lists are zero-based (first element is [0])
>>> horsemen[2] => 'famine'
Allow negative indices which wrap the list
>>> horsemen[-2] => 'pestilence'
Operating on Lists
Slicing a List
Subset specified by two indices. From 1st up to but not
including 2nd
>>> horsemen[1:3] => ['famine', 'pestilence']
Leaving out an index implies first or last
Adding elements
.append adds a single element to the end
.insert places an element at a particular position
.extend concatenates list onto end
Deleting elements
.remove deletes the first occurrence of a value from a list
Searching a List
.index finds first occurrence of a value and returns the
index
More on Lists
Mapping
List comprehension allows a compact way of applying a
function to every element of a list
li2 = [elem*2 for elem in li]
Same as:
j = 1
while j < len(li):
li2[j] = li[j] * 2
Joining Lists into Strings
Join combines a list of strings into a single string
print ";".join(["2b", "or", "not", "2b"]) =>
2b;or;not;2b
Split reverses join
"2b;or;not;2b".split(";") => ['2b', 'or',
'not', '2b']
Tuples
sins = ("pride", "anger", "gluttony",
"envy", "lust", "avarice", "sloth")
An immutable list. No changes allowed
Similar to lists
Defined order, negative indices, zero-based, slicing
But no methods available (except ‘in’)
So what is it good for
Faster than an equivalent list
Write-protects data
Can serve as an immutable dictionary key
Formatting Strings
Can create strings using a formatting (%
placeholder) specifier
Formatting borrowed from ‘c’ language
Concatenation (+) only works when
combining strings
Examples
>>> print "%s two %s" % ("joining",
"strings")
joining two strings
>>> print "today is %d / %d / %d" % (20,
2, 2006)
today is 20 / 2 / 2006
Conclusion
Some details skipped over (import modules,
__name__ for debugging)
Homework: make sure you understand aliasing
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)