+Review & Course Wrap-up
Introduction to Programming - Python
+
Agenda – Week of May 2nd
n Assignment #11 – Due May 4th – no late submissions
accepted!
n Office Hours on Wednesday
n Reviews
n Last Week – Programming Challenges
n Final Exam Format
n OOP
n Dictionary
Day 27
+
In Class Exercises
From This Week
+Programming Challenge:
Deck of Cards
n Create a deck of cards class. Internally, the deck of cards
should use another class, a card class.
n Requirements:
n The Card class should have a suit (Hearts, Diamonds, Clubs,
Spades) and a value (A,2,3,4,5,6,7,8,9,10,J,Q,K)
n The Deck class should have a deal method to deal a single card
from the deck
n There should be a shuffle method which makes sure the deck of
cards has all 52 cards and then rearranges them randomly.
+
Programming Challenge:
Bank Account Class
nCreate a BankAccount class. Your class should support
the following methods:
class BankAccount:
"""Bank Account protected by a pin number."""
def __init__(self, pin):
"""Initial account balance is 0 and pin is 'pin'."""
def deposit(self, pin, amount):
"""Increment account balance by amount and return new
balance."""
def withdraw(self, pin, amount):
"""Decrement account balance by amount and return amount
withdrawn."""
def get_balance(self, pin):
"""Return account balance."""
def change_pin(self, oldpin, newpin):
"""Change pin from oldpin to newpin."""
+
Programming Challenge:
Bank Account Class - Continued
n As you implement your BankAccount class, you should think
about the following:
n What should be stored within the BankAccount class? That is, what
are its instance variables?
n What should happen if the wrong pin is provided for any of the
methods (other than __init__, which is setting the initial pin)?
n What should happen if you try to withdraw more than is in the
account?
n Does your bank account behave as you expect?
n Try depositing and/or withdrawing change, instead of whole
dollar amounts.
n Do you want your real bank account to behave this way?
+
Review for Final Exam
+
Agenda
n Exam format & resources
n Exam topics
n Sample problems
+
Final Exam Format
n Accessibility via NYU Brightspace
n Exam Format
n Multiple Choice—expect up to 10 to 15 questions
n Trace the output and short form questions
n Short Program Questions (approximately 7)
+
Final Exam Topics & Resources
n Go to Course Notes & Slides Section of Course Website
n See ‘Sample Programming Questions and Review Notes’
n Click ‘Review topics and sample practice problems for Final’
n Gaddis
n End of Chapter – Review Questions
+
Intro to OOP
Review Questions
+
Consider the following code:
class Clock:
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)
clock = Clock('5:30')
clock.print_time()
+
+
Consider the following code:
class Clock:
def __init__(self, time):
self.time = time
def print_time(self, time):
print(time)
clock = Clock('5:30')
clock.print_time('10:30')
+
+
Consider the following code:
class Clock:
def __init__(self, time):
self.time = time
def print_time(self):
print(self.time)
boston_clock = Clock('5:30')
paris_clock = boston_clock
paris_clock.time = '10:30'
boston_clock.print_time()
+
+Consider the following code:
class Spell(object):
def __init__(self, incantation, name):
self.name = name
self.incantation = incantation
def __str__(self):
return self.name + ' ' + self.incantation + '\n' + self.get_description()
def get_description(self):
return 'No description'
def execute(self):
print(self.incantation)
class Accio(Spell):
def __init__(self):
Spell.__init__(self, 'Accio', 'Summoning Charm')
class Confundo(Spell):
def __init__(self):
Spell.__init__(self, 'Confundo', 'Confundus Charm')
def get_description(self):
return 'Causes the victim to become confused and befuddled.'
def study_spell(spell):
print(spell)
spell = Accio()
spell.execute()
study_spell(spell)
study_spell(Confundo())
+
+
+
+
+
Dictionaries
n A Dictionary in Python is a sequence object like a list
n Unlike a list, a Dictionary doesn’t use integer based index
values.
n Instead, Dictionaries use immutable objects (like Strings) to
index their content
n In other languages Dictionaries are often referred to as
“Associative Arrays” or “Hashmaps”
+
Lists vs. Dictionaries
n Sequence Structure
n Mutable (can be changed if
you know which index you are
modifying)
n Items are stored in a particular
order based on index values
n Items can be indexed using an
integer
n Sequence Structure
n Mutable (can be changed if
you know which index you are
modifying)
n Items are not stored in any
particular order
n Items can be indexed using
anything that is immutable
(integer, String, etc.)
List Dictionary
+
Creating a Dictionary
n You can create a Dictionary using the curly braces – “{“ and
“}”, like this:
my_dictionary = { }
n This will create an empty Dictionary
+
Adding items to a Dictionary
n In order to add an item to a Dictionary you need to specify a
“key” – this is usually in the form of a String
n You can then associate some data with that key. For example
I could associate the number 3.2 with the key “python” by
doing this:
my_dictionary[“python”] = 3.2
n This will place the number 3.2 into the Dictionary at the
position marked by the String “python”
+
Accessing Dictionary items
n You can access all items in a Dictionary by printing it out, like
this:
print(my_dictionary)
n However, you often just want to access one item – this works
the same as with an array, but you will use a key instead of an
integer index:
print( my_dictionary[“python”] )
+
Creating a Dictionary with Values
n Dictionaries store key / value pairs. You can initialize a Dictionary with
a known set of key / value pairs by using the following syntax:
my_dictionary = {“python”:3.2, “java”:1.8}
my_dictionary = dict([(”python”, 3.2), (“java”,1.8)])
n This will create a Dictionary with the keys “python” and “java”
+
Invalid Indexes
n Note that you cannot access elements in a Dictionary that
have not been defined. This would raise an exception if
“java” was not a key in the Dictionary:
print( my_dictionary[“java”] )
n You can use the “in” operator to test to see if a key is in a
dictionary like this:
if ( “java” in my_dictionary” ):
n Note that this will check for the presence of a key in a
dictionary, not for the data that the key is storing!
+
Iterating over every item in a
Dictionary
n To iterate over every time in a Dictionary you need to be able to
visit every key value (as opposed to simply knowing the size of a
list and iterating over the integer range of the list)
n You can extract all the keys from a Dictionary by doing the
following:
for key in my_dictionary.keys():
n The target variable “key” will assume each key value in your
Dictionary as the loop progresses.
n You can print out all items with their keys by doing the following:
for key in my_dictionary.keys():
print (key, “ == “, my_dictionary[key])
+
Iterating over every item in a
Dictionary
n There is no guarantee that the keys() method will return the
keys of a dictionary in any particular order.
n However, you can ask Python to sort the keys before you
iterate over them, like this:
for key in sorted( my_dictionary.keys() ):
n This will sort the keys in ascending order, which then lets you
access the elements in the dictionary in ascending order.
+
Finding all the values in a
Dictionary
n You can also iterate over just the values in a dictionary (not
just the keys) using this syntax:
for v in my_dictionary.values():
print(v)
n Note that doing this will only expose the values in a
dictionary and not the key – this means that you cannot
change the values in the dictionary using this method. This is
analogous to iterating over a list like this:
for item in my_list:
print(item)
+
Iterating over every item in a
Dictionary
n You can also iterate over a Dictionary by using the following
technique to extract both the key and the value at the same
time:
for key, value in my_dictionary.items():
print(key, value)
+
Other Built-in Dictionary Access
Methods
n d.get([, ])
n Returns a value given a key, i.e., if it exists in the dictionary
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> print(d.get('b’))
??
>>> print(d.get('z’))
??
n d.pop([, ])
n Removes a key from a dictionary—if present — and returns its
value
+
Other Built-in Dictionary Access
Methods
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('b’)
20
>>> d
{'a': 10, 'c': 30}
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop(‘z’)
# what’s returned?
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z', -1)
-1
>>> d
{'a': 10, 'b': 20, 'c': 30}
+
Creating Sets
n Empty sets:
n yaso = set()
n yaso = {} # an alternative
n Populating a set with elements:
n yaso = set([‘a’, ‘b’, ‘c’])
n yaso = {‘a’, ‘b’, ‘c’}
n A set with one element? – think again!
n yaso = set(‘abc’)
+
Dictionary Review Question:
D = dict()
for i in range(3):
for j in range(2):
D[i] = j
print(D)
What’s the output?
+
+
Dictionary Review
D = {1 : [1, 2, 3], 2: (4, 6, 8)}
D[1].append(4)
print(D[1], end = " ")
L = [D[2]]
L.append(10)
D[2] = tuple(L)
print(D[2])
What gets printed?
+
+
+
Dictionary Update?
dictionary1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
dictionary2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
dictionary1.update(dictionary2);
for key, values in dictionary1.items():
print(key, values , end=" ")
What gets printed?
+
+
Accessing Dictionaries
counter = {}
def addToCounter(country):
if country in counter:
counter[country] += 1
else:
counter[country] = 1
addToCounter('China')
addToCounter('Japan')
addToCounter('china')
print(len(counter))
What is the length of this dictionary?
+
+
Opening a file in Python
+
Reading data from a file
n You can read data contained inside a file once you have
created a file object and have opened a file for reading using
the read() function. Here’s an example:
myvar = open("test.txt", "r”)
alldata = myvar.read()
print(alldata)
myvar.close()
+
Writing Numeric Data to a file
n The write() method only accepts strings – the following code
will generate a runtime error:
myvar = open("test2.txt", "w”)
myvar.write(55)
myvar.close()
n You need to convert any data that will be stored in a file into a
string by using the str() conversion function. Example:
myvar = open("test2.txt", "w”)
myvar.write(str(55))
myvar.close()
+
Delimiters & Files
n You want to try and avoid writing files that concatenate all of
your data into one long line of unintelligible text
n This is bad practice since it can be very difficult – or
impossible – to extract out your data later on
n One way to separate data in a text file is by splitting out your
data into multiple lines using the “\n” escape character. This
allows you to store a single value on each line of your text
file, which will make things a lot easier for you later on when
you need to read your file and perform some kind of
operation on the data contained within
+
Exceptions
+
Exceptions
n An exception is any error that causes a program to halt while
it’s running.
n Example:
x = ‘Craig’
y = int(x)
+
Exceptions
n When an exception occurs Python will generate a “traceback”
n Tracebacks give information about the exception that occurred,
including the line number that caused the issue and the name of the
exception
n Programmers generally say that an exception has been “raised” by the
program
+
Preventing Exceptions
n Many times you can avoid exceptions all together by adjusting how
we code our algorithms. For example, the following code will raise
an exception if x = 0
x = int(input(‘give me a number’))
print (100/x)
n Yet we can avoid the issue by wrapping the potentially dangerous
code inside a selection statement:
x = int(input(‘give me a number’))
if x != 0:
print (100/x)
+
Catching Exceptions
n Python has an exception handling statement that can be used to “catch”
exceptions and prevent them from crashing your program
n Syntax:
try:
# questionable code goes here
except:
# this block will run if the code in the
# ‘try’ block above raised an exception
else:
# this block will run if the code in the
# ‘try’ block above was successful
finally:
# this block will run regardless of whether the
# exception is raised
+
Lists
+
Lists in Python
n Lists having the same elements are not the same:
>>> a = ['foo', 'bar', 'baz', 'qux’]
>>> b = ['baz', 'qux', 'bar', 'foo’]
>>> a == b
False
n Lists can contain any data type that we have covered so far. Example:
my_list = [‘Craig’, ‘John’, ‘Chris’]
n Lists can also mix data types. Example:
my_list = [‘Craig’, 5.0, True, 67]
n You can print the value of a list using the print() function. Example:
print(my_list)
+
List Repetition
n You can use the repetition operation (“*”) to ask Python to
repeat a list, much like how you would repeat a string.
Example:
my_list = [1, 2, 3] * 3
print(my_list)
>> [1, 2, 3, 1, 2, 3, 1, 2, 3]
+
List Concatenation
n You can use the concatenation operation (“+”) to ask Python
to combine lists, much like how you would combine strings.
Example:
my_list = [1, 2, 3] + [99, 100, 101]
print(my_list)
+
Indexing List Elements
n In a book you can reference a page by its page number
n In a list, you can reference an element by its index number
n Indexes start at the number zero.
n Example:
my_list = [‘Craig’, ‘John’, ‘Chris’]
print(my_list[0]) # what’s the output?
+
Invalid indexes
n You will raise an exception if you attempt to access an
element outside the range of a list. For example:
my_list = ['Craig', 'John', 'Chris’]
print(my_list[4]) # Index doesn’t exist!
+
Changing the value of an item in a
list
n Lists are “mutable,” which means that they can be changed
once they have been created (unlike strings)
Example:
my_list = [1, 2, 3]
print(my_list)
>> [1,2,3]
my_list[0] = 99
print(my_list)
+
List Mechanics
n List variables are considered “references”
n This means that they “reference” or “point” to a specific region
of your computer’s memory. This behavior can cause some
interesting side effects. For example, the following two list
variables refer to the same list in memory.
mylist1 = [1,2,3]
mylist2 = mylist1
print(mylist1)
print(mylist2)
>> [1,2,3]
>> [1,2,3]
+
List Mechanics
n This means that you can change one of the lists and the
change will be reflected in the other.
mylist1 = [1,2,3]
mylist2 = mylist1
mylist1[0] = 999
print(mylist1) # what gets printed???
print(mylist2)
+
Copying a List
n Python will only create new lists when you use [] syntax to define
a list for the first time
n You can take advantage of this behavior to create true copies of
your list objects. For example:
mylist1 = [1,2,3]
mylist2 = [] + mylist1
mylist1[0] = 999
print(mylist1)
print(mylist2)
>> [999,2,3]
>> [1,2,3]
+
Copying a List – Continued
n Other ways to copy
n Slicing Operator
>>> a = [1, 2, 3, 7]
>>> b = a[:]
>>> b
[1, 2, 3, 7]
n List Function
>>> a = [1, 2, 3, 4]
>>> b = list(a)
>>> b
[1, 2, 3, 4]
n Copy Method1
>>> a = [1, 2, 3, 4]
>>> b = a.copy()
1 Available in Python 3.x only.
+
Creating Lists
n You can create an empty list with no elements using the
following syntax:
mylist = []
n Sometimes you want to create a list that contains a certain
number of “pre-set” elements. For example, to create a list
with 10 elements that are all set to zero you could do the
following:
mylist = [0] * 10
+
List Access
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
print(nameList[1][-1])
What gets printed?
+
+
List Manipulation & Copying
check1 = ['Learn', 'Quiz', 'Practice', 'Contribute']
check2 = check1
check3 = check1[:]
check2[0] = 'Code'
check3[1] = 'Mcq'
count = 0
for c in (check1, check2, check3):
if c[0] == 'Code':
count += 1
if c[1] == 'Mcq':
count += 10
print(count)
What gets printed?
+
+
More List Manipulation
def gfg(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
gfg(3,[3,2,1])
What gets printed?
+
+
Accessing the individual
characters in a String
n Some programming tasks require you to access the individual
characters that are contained within a string.
n You can isolate individual characters within a string by using a
for loop. The target variable in your loop will assume each
character in your string one at a time. For example:
for c in “Craig”:
print (c)
>> C
>> r
>> a
>> i
>> g
+
Looking at the string index
+
String Slicing Notation
n When you ask Python to slice a string you need to use bracket notation
to specify the index range of the characters you wish to extract.
n The syntax for this notation is as follows:
substring = bigstring[start:end:step]
n You must supply at least a start or an ending index value.
n Substrings contain all characters starting at the start value specified and
continue up to (but do not include) the ending value.
n Omitting a starting or ending index value will cause Python to assume
you want to start at the beginning of the string (if you omit a start value)
or you want to continue slicing to the end of the string (if you omit the
end value)
n This should look a lot like the range function!
+
Testing Strings with in and not in
You can also test to see if a string is not in another string by
using the “not” keyword in your expression. Example:
word = "Jackson James John Chris Tom"
if "Johnny" not in word:
print("No Johnny!")
else:
print("Johnny is here!")
+
String Methods
n A “method” is a function that belongs to an “object”, and
performs some operation on that object. Example:
n We really haven’t explored objects much in class as of yet,
but strings can be used as a good introduction to objects and
methods.
n The general syntax for calling a method on an object looks a
lot like a function call, with the notable exception that the
method call generally does not need to pass an argument to
the function specifying which piece of data is being operated
on. Syntax:
stringvariable.method(arguments)
+
String Testing Methods
isalnum()
isalpha()
isdigit()
islower()
isspace()
isupper()
True if all characters are alphanumeric
True if all characters are alphabetic
True if all characters are digits
True is all alpha characters are lower
True if all characters are “whitespace”
True if all alpha characters are upper
Method Output
+
Splitting a string
n We can use a technique called “splitting” to “unpack” a
string and extract its individual values. The trick is to isolate
a “separator” character that can be used to delimit the data
you want to extract. Here’s an example:
mystring = 'Naim,Professor,NYU'
splitstring = mystring.split(',')
print(splitstring)
>> ['Naim', 'Professor', 'NYU']
+
Splitting a String
n General Algorithm:
n Obtain a string that contains data organized in a certain way
n Split the string into a list
n Process the list using list mechanics