These slides were presented at the Intro to Python Workshop in San Diego, California on January 19, 2013. This workshop was for absolute beginners in Python, and builds from the ground up. There were two projectors used in the presentation, one for showing these slides and one with a command-line Python prompt to show the execution of example code throughout the presentation.
The presenters were David Neiss and Kendall Chuang of the San Diego Python Users Group.
Intro to Python Workshop San Diego, CA (January 19, 2013)
1. Introduction
To Python For Beginners
San Diego Python Users Group
Jan 18 & 19, 2013
David Neiss and Kendall Chuang
Tuesday, January 22, 13
2. Thanks to Sponsors:
• Ansir Innovation Center = big thanks for
the space
• Python Software Foundation = $ for food
• San Diego Python Users Group =
volunteers
Tuesday, January 22, 13
3. SD Python Users Group
• Started by Kendall Chuang and David Fischer
• Appx 250 people (not bad, but Boston has appx 3000!)
• Monthly meet-ups
• FREE, Free, free (at last, apologies to MLK)
• Last Thursday of month
• 7:30 (appx 1.5 hours)
• @ Ansir
• Usually one or two speakers
• All experience levels
• Listed on sdtechscene.org and meetup.com
Tuesday, January 22, 13
4. Today’s Overview
• Morning learn & do
• Lunch break around 12 - free pizza and
drinks, about an hour
• Afternoon, continue, learn & do
• Project learn & do
• Bathroom, wifi, breaks
Tuesday, January 22, 13
5. Why Python?
• Free, open source
• Software quality (readability counts!)
• Developer productivity
• Program portability
• “batteries included”, large standard library
• Fun (really? yes, esp. compared to other languages)
• Free books and training, here and online
Tuesday, January 22, 13
6. Why not Python?
• Speed of execution can be an issue, so it
depends... usually not a problem though
• Dynamic typing means errors might not be
detected until run time
Tuesday, January 22, 13
7. Python vs PERL
“you can do everything in Python
that you can do in Perl, but you can
read your code after you do it”
Tuesday, January 22, 13
8. Python Background
• Popularity - within top 6 (depending on on
source, vs C/C++, Java, PHP, Javascript, C#,
Ruby)
• Py* - the name “Python” -> Monty Python
• Guido van Rossum (BDFL)
• 2.x vs 3.x
• > 20 years old, mature (Python not Guido)
Tuesday, January 22, 13
9. Who uses Python?
• Over 1 million programmers (!)
• Intro programming language now @ MIT’s 6.00
Intro to CS (free on Open Courseware),
Stanford’s CS107, Udacity,...
• Google,Yahoo, Facebook, Amazon, CERN,
Qualcomm, NASA, Twitter, Khan Academy, ...
Tuesday, January 22, 13
10. What is Python used
for?
• Scripting backend for web servers, esp.
mod_wsgi for Apache (WSGI)
• Web app frameworks (Google App Engine,
Django, TurboGears,...)
• NumPy, SciPy, MatPlotLib for scientific/
numerical analysis
• And more...
Tuesday, January 22, 13
11. Running Python
Programs
• Two modes:
• As programs
• Source file usually suffixed with .py
• To run, “python hello.py”
• If *nix and shebanged, just “./hello.py”
• Interactively, via shell
• To enter shell, “python”
Tuesday, January 22, 13
12. The Python Interpreter
• The “python” executable
• Compiles Python source code into Python
byte codes as the code is run
• No “pre run compilation step” = faster
development
• Caches compiled code into .pyc files, if can
write to file system
Tuesday, January 22, 13
13. Python Shell
• Fosters “exploratory/interactive programming”
• Prints expression values automatically
• help() - enters into a help mode
• dir() - prints names in module’s namespace
• dir(name) - prints attributes of specified name
• Use up arrow to retrieve last command
• quit via exit()
Tuesday, January 22, 13
14. Do
• Startup the Python shell “python”
• “help()” to enter the help system
• Type “pass” to get help on the pass command
• “quit” to exit help
• “dir()” to get a dump of names in current scope
• “quit()” to exit the Python shell
• “print ‘hello world’” to print out
Tuesday, January 22, 13
15. Let’s get started...
• Comments
• Variables and data types
• Control structures
• Functions
• Modules
• File I/O
• OO and Classes
• Projects
Tuesday, January 22, 13
16. Comments
• A comment is used to enter freehand text,
usually for documentary purposes
• Use a single hashmark to comment #
• Comment ends with new line
# this is a comment
def foo(): # this is the foo func
Tuesday, January 22, 13
17. Do
• type “# isn’t python great?”
• You get ..., continue comment with #. Hit
return to end line
• type “pass # hello world”
• Pass is a NOP Python command
• Does nothing, but shows we can have a
comment at the end of a line
Tuesday, January 22, 13
18. Print Statement
• Before we do anything, we need a way to
look at values, using the print command.
• print <expression>
• <expression> can be a variable or literal, for
example
print “hello world” #literal
print 2 > 1 # an expression
Tuesday, January 22, 13
19. Print Formatting
• Note that you can use single or double quotes
• You can use placeholders in print statements. Use %s for string, %d for
integer, %f for float
print “Let’s talk about how great %s is” %
“david”
print “There are %d types of people” % 2
print “I averaged %f strokes per hole” %
(80./18)
For two values, use a tuple (will be explained
later)
print “I am %s and I have owned %d cars” %
(“david”, 3)
Tuesday, January 22, 13
20. Do
• Print your name
• Print your name and house number using
print formatting string “I am %s, and my
house address number is %d” and a tuple
Tuesday, January 22, 13
21. Data Types
• Programs are composed of data + algorithms
• Understanding data and data structures is
the first step (control structure and
algorithms is the second)
• Data types: bools, numbers, strings, lists,
dictionaries, sets, tuples,...
• later, custom data types via classes
Tuesday, January 22, 13
22. Variables
• Dynamically bound to objects of specific data types
• No need to declare types, type is inferred from
object
• Type of referred object can be determined using
type(variable)
• Advanced - reference counted objects, no need for
managing memory
• id(variable) shows the ID of underlying object
Tuesday, January 22, 13
23. Variable Naming Rules
• Names can be arbitrarily long
• Named can contain letters and numbers
• First character must be a letter
• Can contain upper and lower case
• Case sensitive
• _ underscore is legal
• Don’t use reserved keywords
Tuesday, January 22, 13
24. Do
• Create a variable using your name and assign an
integer of your birth month to it (e.g. “david = 3”)
• Print the variable and print its type
• Assign a string of your birth month to the
variable
• Print the variable and print its type
• Notice that the type of the variable changes with
the data.
Tuesday, January 22, 13
25. Boolean (bool)
• True, False
• case sensitive
• True is an alias for 1, False for 0
• 0 valued data types are False (i.e., [], {}, “”,
0.0), else True
Tuesday, January 22, 13
26. Boolean
• X and Y is True only if both X and Y are True
• X or Y is True if either X or Y is True
• not inverts True to False and False to True
• != is not equal to
• > greater than, < less than, >= greater than or
equal to, <= less than or equal to
• Use == for comparison, single = is for assignment
Tuesday, January 22, 13
27. Do
• print True
• print True == True
• print “hello” == “HELLO”
• print not True
• print 1==1 and 2==3
• print not (True and False)
• print not (True or False)
Tuesday, January 22, 13
29. Numeric Operators
• Usual operators +, -, *, /, **
• +=, *=, /=, -= shortened forms
• Integers have arbitrary precision(!)
• Floating point number must have decimal
point
• Note difference between 5/2 and 5.0/2
Tuesday, January 22, 13
30. Do
• Assign your age as an integer to a variable
• Subtract 10 years from your age
• Raise your age to the 100th power and
print it
Tuesday, January 22, 13
31. Strings
• Use quoted notation
• Single or double quotes, but must match
• Immutable
• len() for length
• type() == str
Tuesday, January 22, 13
33. Do
• Create a variable that has your first and last name
• Print out the first letter of your first name
• Using splicing, extract your last name from the
variable and assign it to another
• Try to set the first letter of your name to lower
case - what happens? why?
• Have Python print out the length of your name
string, hint use len()
Tuesday, January 22, 13
34. String Operations
• Concatenation via +, returns new string combining
both
• Concatenation via *, repeats second string N times
• string.upper(), converts string to upper case
• string.swapcase(), swaps case of chars in string
• string.split(), splits string and returns list of words
• string.count(“whatToCount”)
• string.replace(“this”, ”withThat”)
Tuesday, January 22, 13
35. Do
• Create a string of the concatenation of your first and last names,
Hint use + operator
• Create a new string of your first name followed by “is great” 10
times (hint, use the * operator)
• Print your name in all upper case. Hint, use .upper()
• Split “hello my name is david” into the individual words. Hint,
use .split()
• Count the number of occurrences of “a” in “hello my name is
david”. Hint, use .count(“a”)
• Replace lower case d with upper case in “hello my name is david”.
Hint, use .replace(“d”, “D”). Does this modify the original string?
Tuesday, January 22, 13
36. Lists
• [ ] symbols indicate a list
• Positionally ordered collections of objects. Think of arrays that can change size
• Elements can be of mixed types
• Mutable - fancy term for “can be changed after definition”
• Arbitrary-sized - elements can be added and removed
• Can also use splice operations
• For example
siblings = [“Shelley”,”Mark”,”Gary”]
print siblings[0]
siblings[0] = “Woodie”
print siblings
print type(siblings)
Tuesday, January 22, 13
37. Do
• Create a list of some of your relatives
• Extract the last member from the list in
two different ways (hint, use two different
forms of the index value, positive and
negative)
• Change the name of the second member of
the list to their last name
Tuesday, January 22, 13
38. Lists...
• list.sort()
• list.reverse()
• list.append()
• list.remove()
• list.count(whatToCount)
• bounds checked, throws exception
• Can contain nested data
Tuesday, January 22, 13
39. Do
• Sort the names in your list, hint use .sort()
• Reverse the names in the list, hint use .reverse()
• Append your name to the list, hint
use .append(“yourName”)
• Remove your name from the list, hint
use .remove(“yourName”)
• Count the number of occurrences of your name, hint
use .count(“yourName”)
• Try to set the 100th element of the list to some value.
What happens? Why?
Tuesday, January 22, 13
40. Dictionaries
• Can be created via dict() or {key1:val1, key2:val2, ...}
• Unordered, associative containers
• Mutable, can grow and shrink
• key:value pairs
• values can be nested/complex types
• Specific values are accessed via [key]
• Add new values via [newKey] = ???
• Remove values via del dict[key]
• Accessing undefined values begets an error!
• len() returns number of key/value pairs in dict
Tuesday, January 22, 13
41. Do
• Create an empty dictionary
• Create a dictionary mapping your name to your zip code and
one relative’s name to their zip code
• Print it out
• Add in another relative name & zip
• Print out size of dict
• Change your zip code to any other value and print out the
dict
• Try to access a key value not in the dict. What happens? Why?
Tuesday, January 22, 13
42. Tuples
• Like lists, but immutable
• Used to pass around immutable data
• Constructed either with tuple() or comma-separated set of
values. Note that if you have just one member, use (value,)
• Use [] to access elements
• Supports splicing
• Can contain nested, complex types
• type() == <type ‘tuple’>
• Useful for returning multiple values from a function
Tuesday, January 22, 13
43. Do
• Create a tuple of the names of colors in
the flag
• Print the second element in the tuple
• Try to change the first element of the
tuple. What happens? Why?
Tuesday, January 22, 13
44. Sets
• Unordered collection of unique and immutable objects
• Created by set(iterable) or {values,...}, for example set([1,2,3])
• .add(value) to add a value
• .remove(value) to remove value
• & is intersection, or .intersection()
• | is union or .union()
• - is difference or .difference()
• in operator indicates whether is in set
• .issuperset(), .issubset()
Tuesday, January 22, 13
45. Do
• Create a set of 5 numbers
• Add one number to the set, hint .add(value)
• Remove the first element of the set, hint .remove(value)
• Create a second set having two of the numbers in the
first set
• Determine if second set is a subset of first
• Create a third set as the union of the first two
• Test whether one of the numbers is in the third set
Tuesday, January 22, 13
46. Assignment Operator =
• Assigns object to variable (can lead to aliasing):
a = [1,2,3]
b = a
id(a), id(b)
a[0] = 99
print b # notice that it got changed
• Advanced - use copy operation to make copies/deep copies
b = a[:]
id(a), id(b)
Tuesday, January 22, 13
47. Statements
• calling functions - runs functions
• printing - prints objects
• if/elif/else - selecting actions
• for/else - sequence iteration
• pass - empty placeholder
• break - loop exit
• continue - loop continuation
• def/return - functions and methods, returning from
• global - namespace
• import/from - module access
• class - building objects
• try/except/finally raise - catching and throwing exceptions
• assert - debug checks
Tuesday, January 22, 13
48. if statements
• Used to conditionally perform operations
• Formatted as “if expression:”
• Note the trailing colon which is required - will trip up C/C++
programmers
• Conditional block must be indented, either spaces or tabs
• Example:
a = 11
if a > 10:
print “a is greater than 10”
else:
print “a is less than or equal to 10”
Tuesday, January 22, 13
49. for loops
• Used to iterate over a sequence
sum = 0
for a in [1,2,3,4]:
sum += a
print sum
for b in range(1,10,2):
print b
Tuesday, January 22, 13
50. Do
Compute the product of all
numbers that are a multiple of
5 between 5 and 100, inclusive
Tuesday, January 22, 13
51. Functions
• Why functions?
• Program decomposition
• Code reuse/reduce duplication
• Abstraction/simplification
Tuesday, January 22, 13
52. Functions
• Declare functions with “def name(argList):”
• function name must follow naming rules
• Function body (line following def) must be indented
• argument list is enclosed in parens, def name(arg1, arg2). You
select the argument names that make sense for the function
• End the function with a return statement if you are returning
a value; otherwise, none necessary. Note that function
doesn’t declare its return type
• Functions can call other functions (... and themselves =
recursion, advanced topic)
Tuesday, January 22, 13
53. Arguments
• As usual in Python, argument types are not
declared explicitly
• Arguments are passed “by reference”, so function
can change their values
• If you don’t want function to change values passed
in by reference, make copy[:] or use immutable
type (tuple)
• Advanced - default values, named arguments,
variable number of arguments
Tuesday, January 22, 13
54. Arguments:
def foo(a,b,c):
return a+b+c
• Note that no types are defined for args
• Types must support operations in function
Tuesday, January 22, 13
55. Scopes
• Variables defined within a function are local
to that function
• Use “global” to access variables outside
function scope that are to be assigned
(otherwise, will be local)
Tuesday, January 22, 13
56. Functions...
• def is actually a statement that executes at runtime:
if test:
def func():
print “1”
else:
def func():
print “2”
func() #prints 1 or 2 depending on value of
test
• C/C++/Java/C# programmers, this just seems odd
Tuesday, January 22, 13
57. Do
• Write a function that multiplies input value
by 2
• Try function with both a number and a
string. Do you understand the output in
these two cases?
Tuesday, January 22, 13
58. Modules & Python
Program Structure
• Python files run from top to bottom
• Import statements run their imported files
(modules)
• Imported files may import their own set of
files
Tuesday, January 22, 13
59. Modules
• Modules allow for decomposition of programs
into packages of code & data, to facilitate
• Code reuse
• System namespace partitioning
• Each file is a module, which defines a
namespace
• Modules import other modules to access the
names they define
Tuesday, January 22, 13
60. Modules...
• import modName - lets a client fetch a
module as a whole. Inserts into local
namespace as modName.XXX
• from modName import foo - allows clients
to fetch particular names from a module
into this namespace as foo
• imp.reload modName - provides a way to
reload a module w/o restarting python
Tuesday, January 22, 13
61. Python Program
Structure
• import statements
• function and class definitions
• module scope variables and code
• Code executes from top to bottom of file
(as opposed to main() )
Tuesday, January 22, 13
62. Python program
structure...
def foo(): import a
print “foo” a.foo()
file:a.py file: b.py
• Running a.py does nothing except declare the
foo function
• When B is run, A’s foo is imported as a.foo
• Running b.py prints “foo”
Tuesday, January 22, 13
63. Classes and OOP
• A more advanced topic, minimal coverage here
• OOP, as opposed to functional programming, is
another way to abstract functionality by combining data
and methods that operate on that data
• Can define usage of operators like + and * to make
custom types look like native types (called operator
overloading)
• Useful for expressing hierarchical relationships (called
inheritance) between data types that facilitates code
reuse and a kind of generic programming
Tuesday, January 22, 13
64. Classes
• Objects must be allocated before use
• Allocation may include additional arguments used to construct object
• Methods (or member functions) may be invoked using dotted notation
• Objects can be deleted with del() or simply by overwriting the
reference
• For instance:
from datetime import date
date1 = date(2001,1,1) # allocate instance and supply
construction arguments
type(date1) # type datetime.date, user-defined type
date2 = date(2013,1,1)
delta = date2 - date1 # notice use of difference operator
on user-defined types
print delta.total_seconds() # invoke member function
total_seconds to compute seconds
Tuesday, January 22, 13
65. File I/O
• The File type object is actually built into the
language as a type
• You can only get an instance with the
open(fileName,”rw”) method
• f.read() returns whole file
• f.readln() returns next line
• f.write(data) to write data to file
• f.close() to close file when finished
Tuesday, January 22, 13
66. Do
• Create a file named “test”, open it, and
write “hello world” into it. Hint, f =
open(fileName) and f.write(data)
• Open the file test, and print its contents
• Quit Python shell, and verify that file named
“test” is in dir and contains “helloWorld”
Tuesday, January 22, 13
68. Python Project
• Using your browser, download the Twitter
example and unzip the project on your
computer from here:
• https://github.com/pythonsd/twitter-
example
Tuesday, January 22, 13
69. Project Problem 1
• Run the command python sample_search.py
• The response.json returns the JSON object as
a Python data type. What data type is it? (e.g. ,
List, String, Dictionary, Tuple)
Tuesday, January 22, 13
70. Project Problem 2
• Create a new output text file and write the
response.json to the file
• Open up the output file in another text
editor and check the result
Tuesday, January 22, 13
71. Project Problem 3
• Print out the count of how many “tweets”
there are in the results
• For example
• Tweet Count: n
Tuesday, January 22, 13
72. Project Problem 4
• Create and print a new list of the tweet
‘text’ from the results of the search
Tuesday, January 22, 13
73. Project Problem 5
• Create and print a new list of the tweet
‘from_user’ from the results of the search
Tuesday, January 22, 13
74. Project Problem 6
• From the results, create and print a
dictionary with the ‘from_user’ strings as
the keys and the ‘text’ as the values of a
Python dictionary.
Tuesday, January 22, 13
75. Resources
• http://www.codecademy.com/
• The official Python tutorial: http://
docs.python.org/tutorial/
• Think Python: http://openbookproject.net/
thinkcs/python/english2e/
• Learn Python with games: http://
inventwithpython.com/chapters/
Tuesday, January 22, 13
76. Resources
• Udacity CS 101: http://www.udacity.com/
overview/Course/cs101/CourseRev/apr2012
• Coursera: https://www.coursera.org/course/
programming1
• Learn Python The Hard Way, 2nd Edition
• http://bit.ly/python-lug (Free online)
• Paperback book costs $15.99
• http://learncodethehardway.org
Tuesday, January 22, 13
77. Upcoming Events
• PyLadies
• Join the PyLadies group, encourage women to
learn Python
• Monthly Meeting January 24th
• Meet our regular Python developers
• Django Day February 23
• Learn to program a web app!
• November 2-3, BrightScope
Tuesday, January 22, 13
78. Follow Us
• www.meetup.com/pythonsd
• www.meetup.com/sd-pyladies
• www.pythonsd.org
• groups.google.com/group/pythonsd
• @sandiegopython
Tuesday, January 22, 13