Python Lectures
Python Lectures
I TA M a n i l a
Python
Programming
Language
(Part I - Introducing Python)
2
JM
Instructor
3
Outline
• Part I : Writing scripts and
manipulating data
Some Uses of
What Python Is Capable Of
Python
Game Development
Desktop GUIs
Web
Development
Some Uses of
What Python Is Capable Of
Machine
Data Science
Learning / A.I
7
More than
Not Just Any Language
"Scripting"
• Although Python is often used for "scripting", it is a
general-purpose programming language
Where to get
https://www.python.or g/
Python?
• Site for downloads, community links, etc.
Part
Getting Started
1
10
Running Python
(Windows) Start Menu (IDLE or …)
11
Python Interpreter
All Programs Execute In An Interpreter
• There is no compilation
12
Interactive Mode
• Read-eval loop
>>> print "hello world“
• Executes simple statements typed in directly hello world
>>> 37*42
• This is one of the most useful features 1554
>>> for i in range(5):
... print i
...
0
1
2
3
4
>>>
13
Creating
Programs
• Programs are put in .py files
# helloworld.py
Running Programs
• (IDLE)
Select "Run Module" (F5)
Part
Basics
2
Sample Program
18
Mortgage Computation
Mortgage Computation
20
Sample
Program
Each statement appears
on its own line
No semicolons
21
Comments
Variables
Keywords
Conditionals
if-elif-elsechecks a condition
if expression:
statements
...
elif expression:
statements
...
elif :
statements
...
25
Indentation
Indentation
Primitive Types
Numbers:
• Integer
• Floating Point
Strings
More on Relations
28
Output
Program
31
Takeaways
• If you know another language (Java), you already know a lot
of Python
From Who???
Part
Basic Datatypes and File I/O
3
34
More on Numbers
• Numeric Datatypes
a = True # A boolean (True or False)
b = 42 # An integer (32-bit signed)
c = 81237742123L # A long integer (arbitrary precision)
d = 3.14159 # Floating point (double precision)
More on Strings
• String literals use several quoting styles
a = "Yeah but no but yeah but..."
b = 'computer says no'
c = '''
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes,
not around the eyes,
don't look around the eyes,
look into my eyes, you're under.
'''
Manipulation
• Numeric Datatypes
n = len(s) # Number of characters in s
• String concatenation
s = "Hello"
t = "World"
a = s + t # a = "HelloWorld"
• Slices : s[start:end]
s[1:3] "el"
s[:4] ----> "Hell"
s[-4:] ----> "ello"
37
Coding Challenge
1
Write a python a python script that prints a
bar chart from the given letters.
Coding Challenge 1
38
Requirements
• Length for each character would be random (from 1 to 10 only)
• takes in two letters from the alphabets as an input, one start from and finish to (e.g b, f / a,
l)
Type Conversion
• Numeric Datatypes
a = int(x) # Convert x to an integer
b = long(x) # Convert x to a long
c = float(x) # Convert x to a float
d = str(x) # Convert x to a string
• Examples:
>>> int(3.14)
3
>>> str(3.14)
'3.14'
>>> int("0xff")
255
>>>
40
Input File
• Input file: portfolio.dat
Python Program
42
File I/O
"r" - Read
"w" - Write
"a" - Append
Reading From a
File
Loops over all lines in the file.
Each line is returned as a string.
• f.read([nbytes])
• f.readline()
• f.readlines()
44
String Processing
Strings have various "methods.“
split() splits a string into a list of strings
fields = line.split()
Lists
A 'list' is an ordered sequence of objects.
It's like an array
Types and
Operators
To work with data, it must be converted to an
appropriate type (e.g., number, string, etc.)
String Formatting
Sample Output
49
More on Files
• Opening a file
f = open("filename","r") # Reading
g = open("filename","w") # Writing
h = open("filename","a") # Appending
• Reading
f.read([nbytes]) # Read bytes
f.readline() # Read a line
f.readlines() # Read all lines into a list
• Writing
g.write("Hello World\n") # Write text
print >>g, "Hello World" # print redirection
• Closing
f.close
50
More String
s.find(t)
Methods
s.endswith(suffix) #
#
Check if string ends with suffix
First occurrence of t in s
s.index(t) # First occurrence of t in s
s.isalpha() # Check if characters are alphabetic
s.isdigit() # Check if characters are numeric
s.islower() # Check if characters are lower-case
s.isupper() # Check if characters are uppercase
s.join(slist) # Joins lists using s as delimeter
s.lower() # Convert to lower case
s.replace(old,new) # Replace text
s.rfind(t) # Search for t from end of string
s.rindex(t) # Search for t from end of string
s.split([delim]) # Split string into list of substrings
s.startswith(prefix) # Check if string starts with prefix
s.strip() # Strip leading/trailing space
s.upper() # Convert to upper case
51
More on
Operators
• Python has a standard set of operators
• One difference between Python and text processing tools (e.g., awk, perl,
etc.).
52
Coding Challenge
2
Using data on accidents, list out all accidents
with total count per year
53
Part 4
List & Sets
54
More on Lists
• A indexed sequence of arbitrary objects
fields = ['IBM','50','91.10’]
List Manipulation
• Accessing/changing items : s[n], s[n] = val
fields = [ 'IBM', 50, 91.10 ]
vals[2:4] = ['a','b','c’]
# vals = [0, 1, 'a', 'b', 'c', 4, 5, 6
56
List Manipulation
• Length : len(s)
fields = [ 'IBM', 50, 91.10 ]
len(fields) 3
• Appending/inserting
fields.append('11/16/2007’)
fields.insert(0,'Dave’)
# fields = ['Dave', 'IBM', 50, 91.10, '11/16/2007’
• Deleting an item
del fields[0] # fields = ['IBM',50,91.10,'11/16/2007’]
57
Sets
• Contains an unordered collection of unique and immutable objects
s = {'a', 100, (1,2)}
type(s) #check for type
• To create an empty set we cannot use {} since that would create an empty dictionary:
d = {}
type(d)
More on Sets
• Sets doesn't allow mutable objects
cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))
cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))
Example on Sets
• Count the words in the list in a novel:
for word in ["the", "while", "good", "bad", "ireland", "irish"]:
print("The word '" + word + "' occurs " + \
str(words.count(word)) + " times in the novel!" )
Part
D i c t i o n a r i e s & Tu p l e s
5
62
Python
• Dictionaries
A hash table or associative array
• Sample:
Python
Continuation...
•
Dictionaries
update a dictionary by adding a new entry or modifying an existing entry
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First’}
• can either remove individual dictionary elements or clear the entire contents of a
dictionary
More on
Common Operators...
Dictionaries
• Getting an item
x = prices['IBM’]
y = prices.get('IBM',0.0) # w/default if not found
• Deleting an item
del prices['SCOX’]
65
More on
Dictionaries
• Number of items in a dictionary
n = len(prices)
Example on
Dictionaries
• Given the text below:
• Use dictionary to track the uppercase, lowercase, and other characters in the
string (i.e. kind of grouping the data by uppercase, lowercase, other) - again
ignoring spaces
67
Warm Up
1. Write Python code which accepts name of a product and in
turn returns their respective prices. Make sure to use
dictionaries to store products and their respective prices.
Tuples
• are sequences, just like lists
• differences between tuples and lists are, the tuples cannot be changed unlike lists
and tuples use parentheses, whereas lists use square brackets.
More on
• Ways to write a tuple:
Tuples
t = (x,y,z)
t = x,y,z # ()'s are optional
t = () # An empty tuple
t = (x,) # A 1-item tuple
• To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
Coding Challenge
4
Create a python to combine this data to create a
single dictionary that contains all the words and
their combined frequencies from all these data
sources. Bonus points if you can make your
dictionary sorted by frequency (highest to
lowest).
Coding Challenge 4
71
Other details...
For example, you may have three servers that each return these dictionaries:
d1 = {'python': 10, 'java': 3, 'c#': 8, 'javascript': 15}
d2 = {'java': 10, 'c++': 10, 'c#': 4, 'go': 9, 'python': 6}
d3 = {'erlang': 5, 'haskell': 2, 'python': 1, 'pascal': 1}
d = {'python': 17,
'javascript': 15,
'java': 13,
'c#': 12,
'c++': 10,
'go': 9,
'erlang': 5,
'haskell': 2,
'pascal’: 1}
Coding Challenge 4
72
Other details...
If only 2 dictionaries return data (so d1 and d2), your results would look like:
d = {'python': 16,
'javascript': 15,
'java': 13,
'c#': 12,
'c++': 10,
'go': 9}
73
Day 2
74
I TA M a n i l a
Python
Programming
Language
Day 2
75
Problems will occur D:
Part
Functions
1
78
Functions
• Create functions with the def statemen t
def random_color():
red = randint(0, 255)
green = randint(0,255)
blue = randint(0, 255)
alpha = round(random(), 2)
return red, green, blue, alpha
• Using a function
random_color()
(97, 254, 97, 0.06)
79
Examples on
• Function
Given the data on stocks, read prices into a dictionary
Examples on
• Function
A program that uses our functions
• There are no major surprises with functions--they work like you expect
81
What is a function?
• A function is a sequence of statements
def funcname(args):
statement
statement
...
statement
Function Definitions
• Functions can be defined in any order
Function Definitions
• Functions are treated as building blocks
• The smaller/simpler blocks go first
A Definition Caution
• Functions can be freely redefined!
def foo(x):
return 2*x
print(foo(2)) # Prints 4
print(foo(2,3)) # Prints 6
print (foo(2)) # Error : foo takes two arguments
Scoping of
• All variables assigned in a Variables
function are local
def read_prices(filename):
prices = { }
for line in open(filename):
fields = line.split(',’)
prices[fields[0]] = float(fields[1])
return prices
• So, everything that happens inside a function call stays inside the function
• There's not much to say except that Python behaves in a "sane" manner
86
Global Scoping
• Functions can access names that defined in the same source file (globals)
delimiter = ','
def read_prices(filename):
...
fields = line.split(delimiter)
...
• However, if you're going to modify a global variable, you must declare it using 'global
Parameter Passing
• Parameters are just names for values--no copying of data occurs on function call
def update(prices,name,value):
# Modifies the prices object. This
# does not modify a copy of the object.
prices[name] = value
• If you modify mutable data (e.g., lists or dicts), the changes are made to the original object
prices = {}
update(prices,'GOOG',490.10)
prices
>>> { 'GOOG' : 490.10 }
89
Return Values
• return statement returns a value
def square(x):
return x*x
def bar(x):
statements
return
a = bar(4) # a = None
90
Return Values
• return statement returns a value
def square(x):
return x*x
a = bar(4) # a = None
• Usage examples:
x = divide(37,5) # x = (7,2)
x,y = divide(37,5) # x = 7, y = 2
92
5 Dictionaries
Yo u c a n a s s u m e t h e v a l u e s a r e a l l c o m p a r a b l e a n d
h a v e a n a t u r a l s o r t o r d e r.
Coding Challenge 5
93
Other details...
Your function should return a dictionary that looks like the following:
Part
Modules
2
95
From Functions to Modules
Using a Module
• importing a module
import stockfunc
stocks = stockfunc.read_portfolio("portfolio.dat")
prices = stockfunc.read_prices("prices.dat")
value = stockfunc.portfolio_value(stocks,prices)
• Modules serve as a container for all "names" defined in the corresponding source file (i.e., a
"namespace").
Module Execution
• When a module is imported, all of the statements in the module execute one after another until the end of the
file is reached
• If there are scripting statements that carry out tasks (printing, creating files, etc.), they will run on import
• The contents of the module namespace are all of the global names that are still defined at the end of this
execution process
99
Modules as Objects
• When you import a module, the module itself is a kind of "object"
• You can assign it to variables, place it in lists, change it's name, and so forth
import math
import as statement
• Changing the name of the loaded module
import stockfunc as sf
portfolio = sf.read_portfolio("portfolio.dat")
• This is identical to import except that a different name is used for the module object
• The new name only applies to this one source file (other modules can still import the library using its original
name)
101
prices = read_prices("prices.dat")
• This is useful if a name is used repeatedly and you want to reduce the amount of typing
102
portfolio = read_portfolio("portfolio.dat")
prices = read_prices("prices.dat")
...
• As a general rule, this form of import should be avoided because you typically don't know
what you're getting as a result
• Object-oriented programming
104
Coding Challenge
6
Using data on Ramen, analyze the data to create
at least 5 queries from it. Make sure to
“modularize” your script :D
105
Part
Classes and Objects
3
106
Using Objects
• In a nutshell, object oriented programming is largely about how to bind data and functions together (i.e.,
packaging)
• A string has data (text), but also methods that manipulate that data
107
Using an Object
• Creating an object and calling methods
s = Stock('GOOG',100,490.10)
s.name
>>> 'GOOG'
s.shares
>>> 100
s.value()
>>> 49010.0
s.sell(25)
s.shares
>>> 75
109
Creating Instances
• To create instances, use the class as a function
Instance Data
• Each instance typically holds some state
Calling Methods
• Methods are invoked on an instance
Special Methods
• Classes can optionally hook into operators and other parts of the language by defining so-called "special
methods
115
class Stock(object):
def __init__(self,name,shares,price):
self.name = name
self.shares = shares
self.price = price
def value(self):
return self.shares * self.price
def sell(self,nshares):
self.shares -= nshares
def __repr__(self):
return "Stock('%s',%d,%0.2f)" % \
(self.name,self.shares,self.price)
117
>>> s = Stock('GOOG',100,490.10)
>>> print(s)
Stock('GOOG',100,490.10)
118
Inheritance
• Example
>>> s = Stock('GOOG',100,490.10)
>>> print(s)
Stock('GOOG',100,490.10)
119
Coding Challenge
A
Using your script on the Coding Challenge 4, try
now to implement the 2 solutions below:
Coding Challenge
B
See next slides for details...
Coding Challenge B
121
Other details...
Create a dictionary that contains the number of people that have the eye color as specified in
eye_colors.
The takeaway here is that even if no one matches some eye color, say amber, your dictionary
Other details...
“ P y t h o n Q u e r y To o l ”
124
Main Project: Python Query Tool
Project Overview
• Apply the concepts from functions, modules and classes a.k.a should be
“organized”
• identify the data, check what can be queried (at least 7-10 queries)
• Provide menu of query, can choose only 1
• import / read from CSV file only as datasource -- specific datasource for now
• should have formatted output
• can save query as TXT, CSV and EXCEL