This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
An Introduction To Python - Final Exam Review
1. An Introduction To Software
Development Using Python
Spring Semester, 2015
Class #26:
Final Exam Review
2. 4 Steps To Creating A Python List
1. Convert each of the names into strings by surrounding the
data with quotes.
2. Separate each of the list items from the next with a comma.
3. Surround the list of items with opening and closing square
brackets.
4. Assign the list to an identifier (movies in the preceding code)
using the assignment operator (=).
“COP 2271c” “Introduction to Computation and Programming” 3
“COP 2271c”, “Introduction to Computation and Programming”, 3
[“COP 2271c”, “Introduction to Computation and Programming”, 3]
prerequisites = [“COP 2271c”, “Introduction to Computation and Programming”, 3]
COP 2271c Introduction to Computation and Programming 3
Image Credit: Clipart Panda
3. How To Access A List
• A list is a sequence of elements, each of which has an
integer position or index.
• To access a list element, you specify which index you
want to use.
• That is done with the subscript operator ([] ) in the
same way that you access individual characters in a
string.
• For example:
print(values[5]) # Prints the element at index 5
Image Credit: imgkid.com
4. Appending Elements
• Start with an empty list
goodFood=[]
• A new element can be appended to the end of the list with the append
method:
goodFood.append(“burgers”)
• The size, or length, of the list increases after each call to the append
method. Any number of elements can be added to a list:
goodFood.append(“ice cream”)
goodFood.append(“hotdog”)
goodFood.append(“cake”)
Image Credit: www.pinterest.coma
5. Inserting an Element
• Sometimes, however, the order is important and a new element has to be
inserted at a specific position in the list. For example, given this list:
friends = ["Harry", "Emily", "Bob", "Cari"]
suppose we want to insert the string "Cindy" into the list following the fist
element, which contains the string "Harry". The statement:
friends.insert(1, "Cindy")
achieves this task
• The index at which the new element is to be inserted must be between 0 and the
number of elements currently in the list. For example, in a list of length 5, valid
index values for the insertion are 0, 1, 2, 3, 4, and 5. The element is inserted
before the element at the given index, except when the index is equal to the
number of elements in the list. Then it is appended after the last element:
friends.insert(5, "Bill")
This is the same as if we had used the append method.
Image Credit: www.crazywebsite.comb
6. Finding An Element
• If you simply want to know whether an element is present in a list, use the in
operator:
if "Cindy" in friends :
print("She's a friend")
• Often, you want to know the position at which an element occurs. The index
method yields the index of the fist match. For example,
friends = ["Harry", "Emily", "Bob", "Cari", "Emily"]
n = friends.index("Emily") # Sets n to 1
• If a value occurs more than once, you may want to find the position of all
occurrences. You can call the index method and specify a starting position for the
search. Here, we start the search after the index of the previous match:
n2 = friends.index("Emily", n + 1) # Sets n2 to 4
Image Credit: www.theclipartdirectory.comc
7. Removing an Element
• Pop
– The pop method removes the element at a given position. For example, suppose we start with the
list
friends = ["Harry","Cindy","Emily","Bob","Cari","Bill"]
To remove the element at index position 1 ("Cindy") in the friends list, you use the command:
friends.pop(1)
If you call the pop method without an argument, it removes and returns the last element of the list.
For example, friends.pop() removes "Bill".
• Remove
– The remove method removes an element by value instead of by position.
friends.remove("Cari")
Image Credit: www.clipartpanda.comd
8. Avoiding “Spaghetti Code”
• Unconstrained branching and merging can lead to
“spaghetti code”.
• Spaghetti code is a messy network of possible
pathways through a program.
• There is a simple rule for avoiding spaghetti code:
Never point an arrow inside another branch.
Image Credit: beni.hourevolution.org
9. Spaghetti Code Example
• Shipping costs are $5 inside the United States.
• Except that to Hawaii and Alaska they are $10.
• International shipping costs are also $10.
Need to add Hawaii &
Alaska shipping…
10. Spaghetti Code Example
• You may be tempted to reuse the “shipping cost = $10” task.
• Don’t do that! The red arrow points inside a different branch
12. Boolean Variables
• Sometimes, you need to evaluate a logical condition
in one part of a program and use it elsewhere.
• To store a condition that can be true or false, you use a Boolean variable.
• In Python, the bool data type has exactly two values, denoted False and
True.
• These values are not strings or integers; they are special values, just for
Boolean variables.
• Example:
Here is the initialization of a variable set to True:
failed = True
You can use the value later in your program to make a decision:
if failed : # Only executed if failed has been set to true
Image Credit: www.sourcecon.com
13. Boolean Operators
• When you make complex decisions, you often need
to combine Boolean values.
• An operator that combines Boolean conditions is
called a Boolean operator.
• In Python, the and operator yields True only when
both conditions are true.
• The or operator yields True if at least one of the
conditions is true.
Image Credit: www.java-n-me.com
15. Invert A Condition
• Sometimes you need to invert a condition
with the not Boolean operator.
• The not operator takes a single condition and
evaluates to True if that condition is false and
to False if the condition is true.
if not frozen :
print("Not frozen")
Image Credit: www.clipartpanda.com
16. What Happens When You Call A
Function?
price = round(6.8275, 2)
“Arguments”
Note: Multiple arguments
can be passed to a function.
Only one value can be returned.
17. Benefits Of Using Functions
• The first reason is reusability. Once a function is
defined, it can be used over and over and over again.
You can invoke the same function many times in your
program, which saves you work.
• A single function can be used in several different
programs. When you need to write a new program,
you can go back to your old programs, find the
functions you need, and reuse those functions in
your new program.
• The second reason is abstraction. If you just want to
use the function in your program, you don't have to
know how it works inside! You don't have to
understand anything about what goes on inside the
function.
18. How To Create A Function
• When writing this function, you need to
– Pick a name for the function (selectFlavor).
– Define a variable for each argument (yogurt).
• These variables are called the parameter variables.
• Put all this information together along with the def reserved
word to form the first line of the function’s definition:
def selectFlavor(yogurt) :
• This line is called the header of the function.
Image Credit: imgarcade.com
19. Create The Body Of The Function
• The body contains the statements that are
executed when the function is called.
listOfFlavors = checkInventory()
while flavor in listOfFlavors
print(listOfFlavors[flavor])
if (yogurt) :
selection = input(“Please enter the flavor of yogurt you would like:”)
else :
selection = input(“Please enter the flavor of ice cream you would like:”)
Image Credit: www.pinterest.com
20. Send The Result Back
• In order to return the result of the function,
use the return statement:
return selection
Image Credit: www.clipartpanda.com
21. Final Form Of Our Function
def selectFlavor(yogurt) :
listOfFlavors = checkInventory()
while flavor in listOfFlavors
print(listOfFlavors[flavor])
if (yogurt == 1) :
selection = input(“Please enter the flavor of yogurt you would like:”)
else :
selection = input(“Please enter the flavor of ice cream you would like:”)
return selection
Note: A function is a compound statement, which requires the statements
in the body to be indented to the same level.
Image Credit: www.clipartpanda.com
23. Function Parameter Passing
• When a function is called, variables are created for
receiving the function’s arguments.
• These variables are called parameter variables.
• The values that are supplied to the function when it
is called are the arguments of the call.
• Each parameter variable is initialized with the
corresponding argument.
Image Credit: clipartzebra.com
24. Return Values
• You use the return statement to specify the result of a
function.
• The return statement can return the value of any expression.
• Instead of saving the return value in a variable
and returning the variable, it is often possible to eliminate the
variable and return the value of a more complex expression:
return ((numConesWanted*5)**2)
Image Credit: www.dreamstime.com
25. Scope Of Variables
• The scope of a variable is the part of the
program in which you can access it.
• For example, the scope of a function’s
parameter variable is the entire function.
def main() :
print(cubeVolume(10))
def cubeVolume(sideLength) :
return sideLength ** 3
Image Credit: www.clipartpanda.com
26. Local Variables
• A variable that is defined within a function is called a
local variable.
• When a local variable is defined in a block, it
becomes available from that point until the end of
the function in which it is defined.
def main() :
sum = 0
for i in range(11) :
square = i * i
sum = sum + square
print(square, sum)
Image Credit: www.fotosearch.com
27. Scope Problem
• Note the scope of the variable sideLength.
• The cubeVolume function attempts to read the variable, but it
cannot—the scope of sideLength does not extend outside the
main function.
def main() :
sideLength = 10
result = cubeVolume()
print(result)
def cubeVolume() :
return sideLength ** 3 # Error
main()
Image Credit: www.lexique.co.uk
28. Opening Files: Reading
• To access a file, you must first open it.
• When you open a file, you give the name of the file, or, if the
file is stored in a different directory, the file name preceded
by the directory path.
• You also specify whether the file is to be opened for reading
or writing.
• Suppose you want to read data from a file named input.txt,
located in the same directory as the program. Then you use
the following function call to open the file:
infile = open("input.txt", "r")
Image Credit: www.clipartof.com
29. Opening Files: Writing
• This statement opens the file for reading (indicated by the
string argument "r") and returns a file object that is associated
with the file named input.txt.
• The file object returned by the open function must be saved
in a variable.
• All operations for accessing a file are made via the file object.
• To open a file for writing, you provide the name of the file as
the first argument to the open function and the string "w" as
the second argument:
outfile = open("output.txt", "w")
Image Credit: www.freepik.com
30. Closing A File
• If the output file already exists, it is emptied before the new data is
written into it.
• If the file does not exist, an empty file is created.
• When you are done processing a file, be sure to close the file using the
close method:
infile.close()
outfile.close()
• If your program exits without closing a file that was opened for writing,
some of the output may not be written to the disk file.
• After a file has been closed, it cannot be used again until it has been
reopened.
Image Credit: www.clipartpanda.com
32. Reading From A File
• To read a line of text from a file, call the readline method with
the file object that was returned when you opened the file:
line = infile.readline()
• When a file is opened, an input marker is positioned at the
beginning of the file.
• The readline method reads the text, starting at the current
position and continuing until the end of the line is
encountered.
• The input marker is then moved to the next line.
Image Credit: www.clipartpanda.com
33. Reading From A File
• The readline method returns the text that it read, including the newline
character that denotes the end of the line.
• For example, suppose input.txt contains the lines
flying
circus
• The first call to readline returns the string "flyingn".
• Recall that n denotes the newline character that indicates the end of the
line.
• If you call readline a second time, it returns the string "circusn".
• Calling readline again yields the empty string "" because you have reached
the end of the file. Image Credit: fanart.tv
34. What Are You Reading?
• As with the input function, the readline method can
only return strings.
• If the file contains numerical data, the strings must
be converted to the numerical value using the int or
float function:
value = float(line)
• Note that the newline character at the end of the
line is ignored when the string is converted to a
numerical value.
Image Credit: retroclipart.co
35. Writing To A File
• You can write text to a file that has been opened for writing.
This is done by applying the write method to the file object.
• For example, we can write the string "Hello, World!" to our
output file using the statement:
outfile.write("Hello, World!n")
• The print function adds a newline character at the end of
its output to start a new line.
• When writing text to an output file, however, you must
explicitly write the newline character to start a new line.
Image Credit: olddesignshop.com
36. Writing To A File
• The write method takes a single string as an argument and
writes the string immediately.
• That string is appended to the end of the file, following any
text previously written to the file.
• You can also write formatted strings to a file with the write
method:
outfile.write("Number of entries: %dnTotal: %8.2fn" %
(count, total))
Image Credit: www.freeclipartnow.com
37. Reading Lines From A File
• You have seen how to read a file one line at a time. However, there is a
simpler way.
• Python can treat an input file as though it were a container of strings in
which each line comprises an individual string. To read the lines of text
from the file, you can iterate over the file object using a for loop.
• For example, the following loop reads all lines from a file and prints them:
for line in infile :
print(line)
• At the beginning of each iteration, the loop variable line is assigned a
string that contains the next line of text in the file. Within the body of the
loop, you simply process the line of text. Here we print the line to the
terminal.
Image Credit: www.clipartpanda.com
38. The Split Method
• By default, the split method uses white space
characters as the delimiter. You can also
split a string using a different delimiter.
• We can specify the colon as the delimiter to
be used by the split method. Example:
substrings = line.split(":")
Image Credit: cliparts101.com
39. Reading Characters
• Instead of reading an entire line, you can read individual characters with
the read method.
• The read method takes a single argument that specifies the number of
characters to read. The method returns a string containing the characters.
• When supplied with an argument of 1,
char = inputFile.read(1)
the read method returns a string consisting of the next character in the
file.
• Or, if the end of the file is reached, it returns an empty string "".
Image Credit: www.clipartpanda.com“Z”
40. What Is A Set?
• A set is a container that stores a collection of unique values.
• Unlike a list, the elements or members of the set are not
stored in any particular order and cannot be accessed by
position.
• The operations available for use with a set are the same as
the operations performed on sets in mathematics.
• Because sets need not maintain a particular order, set
operations are much faster than the equivalent list operations
Image Credit: woodridgehomestead.com
41. An Example Of Sets
Cheese Pizza Pepperoni Pizza Meat Lover’s Pizza
• Marinara sauce
• Pepperoni
• Italian sausage
• Slow-roasted ham
• Hardwood smoked
bacon
• Seasoned pork and
beef
• Marinara sauce
• Cheese
• Pepperoni
• Creamy garlic
Parmesan sauce
• Cheese
• Toasted Parmesan
Image Credit: https://order.pizzahut.com/site/menu/pizza
42. Creating & Using Sets
• To create a set with initial elements, you can
specify the elements enclosed in braces,
just like in mathematics:
cheesePizza = {“Creamy Garlic Parmesan
Sauce”, “Cheese”, “Toasted Parmesan”}
Image Credit: https://order.pizzahut.com/site/menu/pizza
43. Creating & Using Sets
• Alternatively, you can use the set function to
convert any list into a set:
cheesePie = [“Creamy garlic
Parmesan sauce”, “Cheese”,
“Toasted Parmesan”]
cheesePizza = set(cheesePie)
Image Credit: www.clker.com
44. Creating & Using Sets
• For historical reasons, you cannot use {} to make an empty set
in Python.
• Instead, use the set function with no arguments:
cheesePizza = set()
• As with any container, you can use the len function to obtain
the number of elements in a set:
numberOfIngredients = len(cheesePizza)
Image Credit: freeclipartstore.com
45. Is Something In A Set?
• To determine whether an element is contained in the set, use
the in operator or its inverse, the not in operator:
if "Toasted Parmesan" in cheesePizza :
print(“A cheese pizza contains Toasted Parmesan")
else :
print(“A cheese pizza does not contain Toasted
Parmesan")
Image Credit: www.clipartpanda.com
46. Sets & Order
• Because sets are unordered, you cannot access the elements of a set by position
as you can with a list.
• Instead, use a for loop to iterate over the individual elements:
print("The ingredients in a cheese pizza are:")
for ingredient in cheesePizza :
print(ingredient)
• Note that the order in which the elements of the set are visited depends on how
they are stored internally. For example, the loop above displays the following:
The ingredients in a Cheese pizza are:
Toasted Parmesan
Creamy garlic Parmesan sauce
Cheese
• Note that the order of the elements in the output can be different from the order
in which the set was created.
Image Credit: www.pinterest.com
47. Sets & Order
• The fact that sets do not retain the initial ordering is not a
problem when working with sets. In fact, the lack of an
ordering makes it possible to implement set operations very
efficiently.
• However, you usually want to display the elements in sorted
order. Use the sorted function, which returns a list (not a set)
of the elements in sorted order. The following loop prints the
pizza ingredients in alphabetical sorted order:
for ingredient in sorted(cheesePizza) :
print(ingredient)
Image Credit: www.itweb.co.za
48. Adding Elements To A Set
• Like lists, sets are collections, so you can add and remove elements.
• For example, suppose we need to add more ingredient to a meat lover’s
pizza. Use the add method to add elements:
meatLoversPizza.add("Mushrooms")
• A set cannot contain duplicate elements. If you attempt to add an
element that is already in the set, there is no effect and the set is not
changed.
Image Creditwww.clipartpanda.com
49. Removing Elements From
A Set
• There are two methods that can be used to remove individual
elements from a set. The discard method removes an element
if the element exists:
meatLoversPizza.discard("Italian sausage")
• The remove method, on the other hand, removes an element
if it exists, but raises an exception if the given element is not a
member of the set.
meatLoversPizza.remove("Italian sausage")
• Finally, the clear method removes all elements of a set,
leaving the empty set:
meatLoversPizza.clear() # no ingredients
Image Credit: www.clker.com
50. Set Union, Intersection, and
Difference
• The union of two sets contains all of the elements from both
sets, with duplicates removed.
• The intersection of two sets contains all of the elements that
are in both sets.
• The difference of two sets results in a new set that contains
those elements in the first set that are not in the second set.
Image Credit: www.abcteach.com
cheesePizza.union(pepperoniPizza) =
{“Marinara sauce”, “Cheese”, “Pepperoni”}
cheesePizza.intersection(pepperoniPizza) =
{“Marinara sauce”, “Cheese”}
cheesePizza.difference(pepperoniPizza) = {“Pepperoni”}
51. What Is A Dictionary?
• A dictionary is a container that keeps
associations between keys and values.
• Keys are unique, but a value may be
associated with several keys.
John
Mike
Ann
Mary
$15,000
$12,000
$30,000
Keys Values
Image Credit: pixgood.com
52. What Is A Dictionary?
• The dictionary structure is also known as a
map because it maps a unique key to a value.
• It stores the keys, values, and the associations
between them.
Image Credit: www.clipartpanda.com
53. Creating Dictionaries
• Each key/value pair is separated by a colon.
• You enclose the key/value pairs in braces,
just as you would when forming a set.
• When the braces contain key/value pairs, they
denote a dictionary, not a set.
• The only ambiguous case is an empty {}. By convention, it denotes an
empty dictionary, not an empty set.
• You can create a duplicate copy of a dictionary using the dict function:
oldSalaries = dict(salaries)
salaries = { “John": 15000, “Ann": 30000, “Mike": 12000, “Mary": 15000 }
Image Credit: www.clipartpal.com
54. Accessing Dictionary Values
• The subscript operator [] is used to return the value associated with a key.
• The statement:
print(“Ann’s salary is", salaries[“Ann"])
prints 30000
• Note that the dictionary is not a sequence-type container like a list.
• Even though the subscript operator is used with a dictionary, you cannot
access the items by index or position.
• A value can only be accessed using its associated key
Image Credit: www.clker.com
55. Searching For Keys
• The key supplied to the subscript operator must be a valid key
in the dictionary or a KeyError exception will be raised.
• To find out whether a key is present in the dictionary, use the
in (or not in) operator:
if “Ann" in salaries :
print(“Ann’s salary is", salaries[“Ann”])
else :
print(“Ann’s salary is not in my list.”)
Image Credit: www.clipartpanda.com
56. Adding and Modifying Items
• You can change a dictionary’s contents after it has been
created.
• You can add a new item using the subscript operator [] much
as you would with a list:
salaries["Lisa"] = 25000
• To change the value associated with a given key, set a new
value using the [] operator on an existing key:
salaries["Lisa"] = 17000
Image Credit: www.articulate.com
57. Removing Items
• To remove an item from a dictionary, call the pop method
with the key as the argument:
salaries.pop(“Mike")
• This removes the entire item, both the key and its associated
value.
• The pop method returns the value of the item being removed,
so you can use it or store it in a variable:
mikesSalary = salaries.pop(“Mike")
Image Credit: imgbuddy.com
58. Avoiding Removal Errors
• If the key is not in the dictionary, the pop method raises a
KeyError exception.
• To prevent the exception from being raised, you can test for
the key in the dictionary:
if "Mike" in salaries :
contacts.pop("Mike")
Image Credit: pixabay.com
59. Traversing a Dictionary
• You can iterate over the individual keys in a dictionary using a
for loop:
print(“Salaries:")
for key in salaries :
print(key)
• The result of this code fragment is shown below:
Salaries:
John
Ann
Mike
Mary
• Note that the dictionary stores its items in an order that is optimized for
efficiency, which may not be the order in which they were added.
Image Credit: tebelrpg.wordpress.com
60. Different Ways Of Doing
The Same Thing
• Lists
– prerequisites = [“COP 2271c”, “Introduction to Computation
and Programming”, 3]
– print(values[5]) # Prints the element at index 5
• Sets
– cheesePizza = {“Creamy garlic”, “Parmesan sauce”,
“Cheese”, “Toasted Parmesan”}
– if "Toasted Parmesan" in cheesePizza :
• Dictionaries
– salaries = {"John": 15000, "Ann": 30000, "Mike": 12000,
"Mary": 15000 }
– print("Ann’s salary is", salaries["Ann"])
Image Credit: www.clipartillustration.com
61. What If Your Cool Functions Were
In A Different File?
• What if your main code was in a file called “main”
and your functions were in a file called “extras”?
How could main use the functionality in extras?
• The import statement tells Python to include the
extras.py module in your program. From that point
on, you can use the module’s functions as if they
were entered directly into your program, right?
Image Credit: www.qubewifi.commain-1
62. Python & Namespaces
• All code in Python is associated with a namespace.
• Code in your main Python program (and within IDLE’s shell) is
associated with a namespace called __main__.
• When you put your code into its own module, Python
automatically creates a namespace with the same name as
your module.
• So, the code in your module is associated with a namespace
called __extras__.
Image Credit: wihdit.wihd.org
63. Python & Namespaces
• When you want to refer to some function from a module
namespace other than the one you are currently in, you need
to qualify the invocation of the function with the module’s
namespace name.
• So, instead of invoking the function as
encryptSS(patients[patientID][9]) you need to qualify the
name as extras.encryptSS(patients[patientID][9]).
• That way, the Python interpreter knows where to look. The
format for namespace qualification is: the module’s name,
followed by a period, and then the function name.
Image Credit: www.greenforage.co.uk-2
64. Python & Namespaces
• If you use
from extras import deEncryptSS, encryptSS
the specified functions (deEncryptSS, encryptSS in this case) are
added to the current namespace, effectively removing the requirement for
you to usenamespace qualification.
• But you need to be careful. If you already have functions called
deEncryptSS or encryptSS defined in your current namespace, the
specific import statement overwrites your function with the imported one,
which might not be the behavior you want.
Image Credit: vistaproblems.com-3
65. What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
DictionaryLists And/Or/Not Functions Files ExceptionSets Modules
Editor's Notes
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
I’m willing to pay you to do that.