You are on page 1of 125

1

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

• Part II : Getting organized (functions,


modules, objects)
4
What is Python?
• an interpreted, object-oriented, high-
level programming language with
dynamic semantics.

• a language that's similar to Perl, Ruby,


Tcl, and other so-called "scripting
languages“

• Created by Guido van Rossum around


1990.
5

Some Uses of
What Python Is Capable Of

Python
Game Development
Desktop GUIs
Web
Development

Database Network Programming


Access
6

Some Uses of
What Python Is Capable Of

Python Big Data

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

• Major applications are written in Python

• Large companies you have heard of are using


hundreds of thousands of lines of Python
8

Where to get
https://www.python.or g/
Python?
• Site for downloads, community links, etc.

• Current production version: Python-3.7.x

• Supported on virtually all platforms


9

Part
Getting Started
1
10
Running Python
(Windows) Start Menu (IDLE or …)
11

Python Interpreter
All Programs Execute In An Interpreter

• If you give it a filename, it interprets the statements


in that file in order

• Otherwise, you get an "interactive" mode where


you can experiment

• 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

print "hello world“

• Source files are simple text files

• Create with your favorite editor (e.g., VS Code)

• Note: There may be special editing modes

• There are many IDEs (too many to list)


14
Creating
Programs
Creating a new program in
IDLE
15
Creating
Programs
Editing a new program in
IDLE
16

Running Programs
• (IDLE)
Select "Run Module" (F5)

• Will see output in IDLE shell window)


17

Part
Basics
2
Sample Program
18

Mortgage Computation

• Given that Andy has taken out a PHP500,000 mortgage from


Guido's Mortgage, Stock, and Viagra trading corporation.

• He got a rate of 4% and a monthly payment of only PHP499.

• However, Guido, being kind of soft-spoken, didn't tell Andy that


after 2 years, the rate changes to 9% and the monthly
payment becomes PHP3999.
Sample Program
19

Mortgage Computation
20

Sample
Program
Each statement appears
on its own line

No semicolons
21

Comments

# starts a comment which


extends to the end of the line
22

Variables

• Variables are declared by


assigning a name to a
value.

• Same name rules as C


([a-zA-Z_][a-zA-Z0-9_]*)

• You do not declare types


like int, float, string, etc.

• Type depends on value


23

Keywords

• Python has a set of


keywords
24

Conditionals
if-elif-elsechecks a condition
if expression:
statements
...
elif expression:
statements
...
elif :
statements
...
25

Indentation

: indicates that an indented


block will follow
26

Indentation

Python only cares about consistent


indentation in the same block
27

Primitive Types
Numbers:
• Integer
• Floating Point

Strings
More on Relations
28

• Boolean expressions: and, or, not

if b >= a and b <= c:


print "b is between a and c"
if not (b < a or b > c):
print "b is still between a and c"

• Don't use &&, ||, and !

• Relations do not require surrounding ( )


29

Output

Print writes to standard output


• Items are separated by spaces
• Includes a terminating newline
• Works with any Python object
Running the
30

Program
31

Takeaways
• If you know another language (Java), you already know a lot
of Python

• Python uses standard conventions for statement names,


variable names, numbers, strings, operators, etc.

• There is a standard set of primitive types such as integers,


floats, and strings that look the same as in other languages.

• Indentation is most obvious "new" feature


Getting Help
32

From Who???

• If Online help is often available


• help() command (interactive mode)
• Documentation at http://python.org
33

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)

• Integer operations that overflow become longs


>>> 3 ** 73
67585198634817523235520443624317923L
>>> a = 72883988882883812
>>> a
72883988882883812L
>>>

• Create with your favorite editor (e.g., VS Code)


>>> 5/4
1
>>>
35

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.
'''

• Standard escape sequences work (e.g., '\n')

• Triple quotes capture all literal text enclosed


Basic String
36

Manipulation
• Numeric Datatypes
n = len(s) # Number of characters in s

• String concatenation
s = "Hello"
t = "World"
a = s + t # a = "HelloWorld"

• Strings as arrays : s[n]


s = "Hello"
s[1] ----> 'e'
s[-1] ----> ‘o’

• 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)

• first letter should always be a previous from the sequence


39

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

• The data: Name, Shares, Price per Share


41

Python Program
42

File I/O
"r" - Read
"w" - Write
"a" - Append

Files are modeled after C stdio.

• f = open() - opens a file


• f.close() - closes the file

Data is just a sequence of bytes


43

Reading From a
File
Loops over all lines in the file.
Each line is returned as a string.

Alternative reading methods:

• f.read([nbytes])
• f.readline()
• f.readlines()
44

String Processing
Strings have various "methods.“
split() splits a string into a list of strings

line = 'IBM 50 91.10\n

fields = line.split()

fields = ['IBM', '50', '91.10']


45

Lists
A 'list' is an ordered sequence of objects.
It's like an array

fields = ['IBM', '50', '91.10']


46

Types and
Operators
To work with data, it must be converted to an
appropriate type (e.g., number, string, etc.)

Operators only work if objects


have "compatible" types
47

String Formatting

% operator when applied to a


string, formats it.
Similar to the C printf() function.

format string values


48

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

• Have different behavior depending on the types of operands.


>>> 3 + 4 # Integer addition7
>>> '3' + '4' # String concatenation'34’
>>>

• This is why you must be careful to convert values to an appropriate type.

• 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’]

• Can contain mixed types

fields = ['IBM',50, 91.10]

• Can contain other lists:


portfolio = [ ['IBM',50,91.10],
['MSFT',200,51.23],
['GOOG',100,490.10] ]
55

List Manipulation
• Accessing/changing items : s[n], s[n] = val
fields = [ 'IBM', 50, 91.10 ]

name = fields[0] # name = 'IBM’


price = fields[2] # price = 91.10
fields[1] = 75 # fields = ['IBM',75,91.10]

• Slicing : s[start:end], s[start:end] = t


vals = [0, 1, 2, 3, 4, 5, 6]
vals[0:4] [0, 1, 2, 3]
vals[-2:] [5, 6]
vals[:2] [0, 1]

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

More List Methods


s.append(x) # Append x to end of s
s.extend(t) # Add items in t to end of s
s.count(x) # Count occurences of x in s
s.index(x) # Return index of x in s
s.insert(i,x) # Insert x at index i
s.pop([i]) # Return element i and remove it
s.remove(x) # Remove first occurence of x
s.reverse() # Reverses items in list
s.sort() # Sort items in s in-plac
58

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)

• Instead, we have to use the set() function:


x = set(["Perl", "Python", "Java"])
s1 = set([1, 2, 3])
s = set(range(10))
59

More on Sets
• Sets doesn't allow mutable objects
cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))
cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))

• Though sets can't contain mutable objects, sets are mutable


cities = set(["Frankfurt", "Basel","Freiburg"])
cities.add("Strasbourg")

• Instead, we have to use the set() function:


x = set(["Perl", "Python", "Java"])
s1 = set([1, 2, 3])
s = set(range(10))
60

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!" )

• Given the list of novels in txt format, count all words


novels = ['sons_and_lovers_lawrence.txt',
'metamorphosis_kafka.txt',
'the_way_of_all_flash_butler.txt',
'robinson_crusoe_defoe.txt',
'to_the_lighthouse_woolf.txt',
'james_joyce_ulysses.txt',
'moby_dick_melville.txt']
for novel in novels:
txt = open("books/" + novel).read().lower()
words = re.findall(r"\b[\w-]+\b", txt)
diff_words = set(words)
n = len(diff_words)
print("{name:38s}: {n:5d}".format(name=novel[:-4], n=n))
61

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

• Sometimes called "dict“

• Sample:

prices = { 'IBM' : 117.88, 'MSFT' : 28.48, 'GE' : 38.75, 'CAT' :


75.54, 'GOOG' : 527.80 }

• Allows random access using key names:

print ("dict[‘GE’]: ", dict[‘GE’])


print ("dict['Age']: ", dict['Age'])
63

Python
Continuation...


Dictionaries
update a dictionary by adding a new entry or modifying an existing entry
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First’}

dict['Age'] = 8; # update existing entry


dict['School'] = "DPS School"; # Add new entry

• can either remove individual dictionary elements or clear the entire contents of a
dictionary

• delete entire dictionary in a single operation

del dict['Name']; # remove entry with key 'Name'


dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
64

More on
Common Operators...
Dictionaries
• Getting an item
x = prices['IBM’]
y = prices.get('IBM',0.0) # w/default if not found

• Adding or modifying an item


prices['AAPL'] = 145.1

• Deleting an item
del prices['SCOX’]
65

More on
Dictionaries
• Number of items in a dictionary
n = len(prices)

• Getting a list of all keys (unordered)


names = list(prices)
names = prices.keys()

• Getting a list of all values (unordered)


prices = prices.values()
66

Example on
Dictionaries
• Given the text below:

• Count how many times each character occurred

• 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.

2. List out all the odd numbers from 1 to n using lists in


Python.
68

Tuples
• are sequences, just like lists

• sequence of immutable Python objects.

• differences between tuples and lists are, the tuples cannot be changed unlike lists
and tuples use parentheses, whereas lists use square brackets.

tup1 = ('physics', 'chemistry', 1997, 2000)


tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
69

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.

print("tup1[0]: ", tup1[0])


70

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}

Your resulting dictionary should look like this:

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:

• If you write a useful script, it will grow features


• You may apply it to other related problems
• Over time, it might become a critical application
• And it might turn into a huge tangled mess
• So, let's get organized...
76
Day 2
Overview

• In this section, we focus our attention on writing larger programs


• Functions
• Modules and libraries
• Creating user-defined objects (classes)
• Metaprogramming
• We'll also look at some standard library
77

Part
Functions
1
78

Functions
• Create functions with the def statemen t

from random import randint, random

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

# Read prices into a dictionary


def read_prices(filename):
prices = { }
for line in open(filename):
fields = line.split(',’)
prices[fields[0]] = float(fields[1])
return prices

# Calculate current value of a portfolio


def portfolio_value(stocks,prices):
return sum([s['shares']*prices[s['name’]]
for s in stocks])
80

Examples on
• Function
A program that uses our functions

# Calculate the value of Users's portfolio


stocks = read_portfolio("portfolio.dat")
prices = read_prices("prices.dat")
value = portfolio_value(stocks,prices)
print("Current value", value)

• 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

• Any Python statement can be used inside


• This even includes other functions
• So, there aren't many rules to remember
82

Function Definitions
• Functions can be defined in any order

• Functions must only be defined before they are actually


used during program execution

• Stylistically, it is more common to see functions defined


in a "bottom-up" fashion
83

Function Definitions
• Functions are treated as building blocks
• The smaller/simpler blocks go first

• Functions must only be defined before they are actually


used during program execution

• Stylistically, it is more common to see functions defined


in a "bottom-up" fashion
84

A Definition Caution
• Functions can be freely redefined!
def foo(x):
return 2*x

print(foo(2)) # Prints 4

def foo(x,y): # Redefine foo(). This replaces


return x*y # foo() above.

print(foo(2,3)) # Prints 6
print (foo(2)) # Error : foo takes two arguments

• A repeated function definition silently replaces the previous definition


• No overloaded functions (vs. C++, Java).
85

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

line_num = 1 # Current line number (a global)


def parse_file(filename):
global line_num
for line in open(filename):
# Process data
...
line_num += 1
87

Default and Keyword Args


• Functions may take optional arguments
def read_prices(filename,delimeter=None):
prices = { }
for line in open(filename):
fields = line.split(delimeter)
prices[fields[0]] = float(fields[1])
return prices

• Functions can also be called with named args


p = read_prices(delimeter=',',filename="prices.csv")
88

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

• If no return value, None is returned

def bar(x):
statements
return

a = bar(4) # a = None
90

Return Values
• return statement returns a value
def square(x):
return x*x

• If no return value, None is returned


def bar(x):
statements
return

a = bar(4) # a = None

• Return value is discarded if not assigned/used


square(4) # Calls square() but discards result
91

Multiple Return Values


• A function may return multiple values by returning a tuple
def divide(a,b):
q = a // b # Quotient
r = a % b # Remainder
return q,r # Return a tuple

• Usage examples:
x = divide(37,5) # x = (7,2)
x,y = divide(37,5) # x = 7, y = 2
92

Coding Challenge Functions &

5 Dictionaries

Write a Python function that will create and return a


d i c t i o n a r y f r o m a n o t h e r d i c t i o n a r y, b u t s o r t e d b y
value.

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...

For example, given the following dictionary:

composers = {'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35}

Your function should return a dictionary that looks like the following:

sorted_composers = {'Wolfgang': 35,


'Frederic': 39,
'Ludwig': 56,
'Johann': 65}

Hint: you'll likely want to use Python's sorted function.


94

Part
Modules
2
95
From Functions to Modules

• As programs grow, you will probably want to have


multiple source files
• Also to create programming libraries
• Any Python source file is already a module
• Just use the import statement
96
A Sample Module
def read_portfolio(filename):
lines = open(filename)
fields = [line.split() for line in lines]
return [ { 'name' : f[0],
'shares' : int(f[1]),
'price' : float(f[2]) } for f in fields]

# Read prices into a dictionary


def read_prices(filename):
prices = {}
for line in open(filename):
fields = line.split(',’)
prices[fields[0]] = float(fields[1])
return prices

# Calculate current value of a portfolio


def portfolio_value(stocks,prices):
return sum([s['shares']*prices[s['name']]
for s in stocks])
97

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").

• The contents accessed through module name


98

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

m = math # Assign to a variable


x = m.sqrt(2) # Access through the variable
print(x)
100

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

from module import


• Selected symbols can be lifted out of a module and placed into the caller's namespace

from stockfunc import read_prices

prices = read_prices("prices.dat")

• This is useful if a name is used repeatedly and you want to reduce the amount of typing
102

from module import *


• Takes all symbols from a module and places them into the caller's namespace

from stockfunc import *

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

• Namespaces are good


103
Insights
Le t ’s pa us e a nd look ba c k …

• Functions and modules form the foundation of a lot of


Python programming

• The final step is to define your own object

• 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)

• You have already been using objects

• For example : strings

• A string has data (text), but also methods that manipulate that data
107

Defining New Objects


• You can define your own custom objects

• Use the class statement


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

• It's just a collection of functions (usually)


108

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

Classes and Methods


• A class is a just a collection of "methods"

• Each method is just a function

• Note: these are just regular Python function definitions


110

Creating Instances
• To create instances, use the class as a function

• This calls __init__() (Initializer)


111

Instance Data
• Each instance typically holds some state

• Created by assigning attributes on self


112

Methods and Instances


• Methods always operate on an "instance"

• Passed as the first argument (self)

• "self" is where the data associated with each instance is located


113

Calling Methods
• Methods are invoked on an instance

• Instance is passed as first paramete


114

Special Methods
• Classes can optionally hook into operators and other parts of the language by defining so-called "special

methods
115

Playing with Special


Methods
• If you use dir() on built-in objects, you will see a lot of the special methods defined
116

Special Method Example


• If you use dir() on built-in objects, you will see a lot of the special methods defined

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

Special Method Example


• Example

>>> 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:

a: Using defaultdict objects

b: Using Counter objects


120

Coding Challenge
B
See next slides for details...
Coding Challenge B
121

Other details...

Suppose you have a list of all possible eye colors:

eye_colors = ("amber", "blue", "brown", "gray", "green", "hazel", "red", "violet")

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

should still contain an entry "amber": 0


Coding Challenge B
122

Other details...

Starter code: class Person:


def __init__(self, eye_color):
self.eye_color = eye_color

from random import seed, choices


seed(0)
persons = [Person(color) for color in choices(eye_colors[2:], k = 50)]

Sample Output: {'amber': 0,


'blue': 0,
'brown': 3,
'gray': 10,
'green': 8,
'hazel': 7,
'red': 10,
'violet': 12}
123

Main Coding Project:


For Day 1

“ P y t h o n Q u e r y To o l ”
124
Main Project: Python Query Tool
Project Overview

• a python script that can be executed from the


command line which will be able to make queries from
the given data (at least 7-10)

• no GUI but at least have a presentable menu


125
Main Project: Python Query Tool
Project Requirements

• 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

You might also like