SlideShare a Scribd company logo
An Introduction To
Software Development
Using Python
Spring Semester, 2015
Class #27:
Final Exam Review
Welcome To TDD!
• When you are creating test cases before you write code and
then letting those test cases drive how you create your code,
you are using Test Driven Development (TDD).
• TDD is a formal term that is used to describe the process of
testing from the outset of development.
• This means that you write every line of code specifically as a
response to your tests.
Image Credit: revistanautilus.ro
TDD Rule #1
• TDD Rule #1: Your test should always fail before you
implement any code.
• You want your tests to fail when you first write them.
• The point of the test is to establish a measurable
success.
• Because your test is failing, now it’s clear what you
have to do to make sure that test passes.
Image Credit: www.fs.usda.gov
3 Steps To Test Driven Development
• Red: Your Test Fails
– Write a test to check whatever functionality you are going to write.
– It will fail because you have not yet implemented that functionality.
– This is the red stage because your testing GUI will show the test in red (failing).
• Green: Your Test Passes
– Implement the functionality to get that test to pass
– Write the simplest code possible to get the test to pass.
– This is the green stage.
• Refactor: Clean up – duplication, ugly code, old code, etc.
– After your test passes, go back in and clean up things that you noticed while
implementing your code.
– This is the refactor stage.
– Next, go on to create the next test.
Pay with
Visa
3
Pay with Visa / MC / Paypal
Image Credit: cliparts.co
What Does Testing First Buy Us?
• Testing produces better code
• Create well-organized code
– Simpler code
– Nothing that is not absolutely required
• Code that always does the same thing
– Production code does the same thing as testing code
– We are writing production code all the time
• Code is loosely coupled
– Tightly coupled code is brittle and breaks easily
– Our code will be broken into a loosely coupled flexible system
Image Credit: www.fotosearch.com
System Testing
• Have to use the system in order to ensure that it
works.
– Dedicated end-to-end system testing period
– Let the real users work on the system
• Test the system in a situation that is as close to real-
world as is possible.
• System testing is all about reality – the system as a
whole, not the individual parts.
Image Credit: cpsobsessed.com
Why Do System Testing?
• Unit testing is a great way to make sure that your specific piece of code
works.
• Unit testing can miss the bugs that only show up when different pieces of
code are hooked together or when real users start to use the system.
• System testing hooks everything together and treats the system like a
black box. The goal is to test the functionality that the user expects.
System testing exercises the functionality of the
system from front-to-back using real-world, black
box scenarios.
Image Credit: joyin6th.blogspot.com
Good System Testing Requires
Two Iteration Cycles
• Iterations allow the
development team to stay
focused
• Provide checkpoints with
customers
• You need the same things for
good system testing
• How about having two cycles of
iteration going at the same
time?
Iteration
1
Iteration
2
Iteration
3
Fix
Bugs
Prep
for IT
1
Test It. 1
Build
Test It. 2
Build
Test It. 3
Build
Test team signs off on working version
How To Deal With BUGS!
A tester finds a bug
• Could be a fail
• Poor documentation
• Missing feature
Tester files a bug
report
• Track bugs!
• Level of detail is
critical
• What were you
trying to do?
• Error messages?
• Steps to recreate
• Expected outcome
Create a story / task to
fix the bug
• Create bug fix story
• Add tasks as needed
• Tough to estimate
Image Credit: www.publicdomainpictures.net
How To Deal With BUGS!
Fix the bug
• Part of an iteration
• Create the test first
• Mark bug as fixed on
bug tracker
• Don’t mark as tested
/ closed / or verified. Check the fix
• Tester / original
reporter tests the
change
• Now bug can be
marked as “closed”
Update bug report
• Close the bug report
• Use report as a script
for retest
• Do not delete it – you
may need to refer
back to it
Image Credit: www.dreamstime.com
Why Create A Bug Report?
• A “bug” is an issue that you HAVE to address
• Bugs have to be recorded and tracked
• Popular free bug tracking program: Bugzilla
• Use your bug tracker to do the following:
– Record and communicate bug priorities
– Keep track of everything
– Generate metrics
Image Credit: vector.me
The Software Development Process
• A good software process is all about
prioritization.
• Make sure that you are doing the right thing
on the project at all times.
• Goal: produce working code. Second goal:
produce quality code
• Always be improving your process
Image Credit: www.clipartof.com
3 Things That Make
Working Software
• Completing an iteration’s scheduled work
– Burn down rate indicates how well your iteration
went
– If you didn’t end on time, but got work done and
the customer is happy then it was all good
• Passing all of the tests
– Unit tests, system tests, black / white box tests
• Satisfying your customer
Image Credit: www.clipartlord.com, www.clipartpanda.com
Things To Do At The Start Of A
New Iteration
• Revise both story and task estimates
– You now have more knowledge about how things will work
– Revisit estimates for remaining user stories and associated tasks
• Revise velocity
– Probably used an initial value of 0.7 (30% wasted)
– Use hard data to recalculate new velocity
– Goal is to provide customer with confident statements
• Recalculate your estimates and velocity at the start of every
iteration, applying what you learned from the previous
iteration
Image Credit: www.fotosearch.com
Change Causes 3 Things To Have To
Be Updated
• User Stories
– Every change to the code has to be documented by a user story
– In this case, the customer’s ability to post a review of their stay needs
to have a user story created for it
• Estimates
– Every user story needs an estimate
– How much time will it take to code that function?
– How much time will it take to integrate that function with other code?
• Priorities
– The customer has to assign a priority to each user story
– You then need to plan out the work for the next iteration
Image Credit: www.fotosearch.com
What To Do When Bugs Are
Discovered
• Software bugs are going to have an impact on your
iteration schedule – they have to be fixed
• Talk with the team – if the bug’s impact is going to be
significant (functionality / schedule) then you are
going to have to talk with your customer.
• You’ll need to have an estimate as to when you can
have this bug fixed.
Image Credit: www.clipartpanda.com
Spike Testing
• Spike Testing: doing one burst of activity, observing
what you accomplish, using that to estimate how
much time it will take to get everything done.
• One possible spike testing plan:
– Take one week to conduct your spike test
– Pick a random sample to fix from the tests that are failing
– At the end of the week calculate your bug fix rate:
Bugs Fixed
5
= your daily bug fix rate
Image Credit: states.phillipmartin.info
What Will Your Spike Test Results
Reveal?
• Test cases revealed how much of your code was failing. Your
spike tests should reveal how long it is going to take you to fix
your bugs.
• Example: 4
5
Total # bugs
How long will it take to fix all bugs?
Bug fix rate x # of bugs = # days required to fix all bugs
0.8 x (13-4) = 7 days
Bugs fixed during spike testing
Image Credit: www.dreamstime.com
Functional Decomposition
• Decompose a function or a module into smaller modules,
which will be composed together to form the bigger module.
• Example: College course registration & enrollment
• Four tasks need to be done:
– Modify and delete students from the database
– Modify and delete courses from the database
– Add, modify, and delete sections for a given course
– Register and drop students from a section
Modular Decomposition For
Student Registration System
Numbering is used to keep track
of the parents of modules.
What Makes A Good
Implementation?
• Readability – can be easily read an understood by other programmers
• Maintainability – code can be easily modified and maintained
• Performance – the code should run as fast as possible
• Traceability – all code needs to be able to be traced back to a user story
• Correctness – the code needs to do what it is supposed to do
• Completeness – all system requirements must be met
Note that each of these requires a trade off. Performance optimization may
decrease the code’s readability and maintainability…
Image Credit: www.dreamstime.com
Comments
• Comments are important
• Comments can help or hurt program readability and
maintainability.
• Two main problem with comments:
– They may distract from the code and make a section more difficult to
read
– They may be wrong
• Comments may become outdated as the code changes.
• Comments may be wrong from the start because they are
never executed/tested.
Image Credit: www.clipartpanda.com
Comments Are A Trade-Off
• We need to recognize the trade-off that comments represent.
• Comments can help to clarify code and relate it to other
sources.
• They also represent some level of duplication of the code.
• It takes time to both create them and then to maintain them.
• Comment errors can be very hard to both find and correct.
Image Credit: www.fotosearch.com
Comment Dangers!
• Comments can be used to justify bad coding practices
• Programmers may be tempted to create code that is too
complicated or too hard to maintain and then add comments
to it instead of rewriting it to better coding standards.
• An alternative: code that is so well written that it documents
itself (“self documenting code”).
• Good goal, but comments still have a place in capturing the
programmer’s intent.
Image Credit: www.clipartof.com
Debugging
• Debugging is all about locating and fixing
errors in the code.
• Generally errors are found by testing, but they
can also be reported by users or code
inspections.
• Debugging is a highly iterative process.
Image Credit: www.clker.com
Performance Optimization
• Performance for any program is important, but…
• Optimizing for performance almost always affects code maintainability
and readability for the worse.
• Real-time systems are the exception – they are all about performance.
• Programmers often make the mistake of worrying about performance too
early in the development cycle.
– Get the code to work first and make it easy to maintain
– If the performance is unsatisfactory, then you can optimize performance – most times
this won’t be an issue.
– Most code is only executed a few times and does not impact performance
– Only a few pieces of code will have to be optimized for performance
Image Credit: www.istockphoto.com
How To Optimize Performance
• Start with a profiler tool
– Runs the program and calculates how much time is spent in each part.
– Helps you to find bottlenecks and to determine what code needs to be
optimized
• Now review and optimize only those modules that will have
an impact on performance
• After making changes, run the profiler again to determine
impact and to ensure changes actually boosted performance.
Image Credit: www.dreamstime.com
The Cost Of Optimization
• A cost / benefit analysis should be done before
performing any performance optimization.
• A programmer’s time is more expensive than
computer time – it may be cheaper to just buy faster
hardware.
• You need to weigh the increase in performance
against the decrease in maintainability and the
possibility of introducing errors.
Image Credit: www.clipartpanda.com
Refactoring
• Just like a novel can be made better by rewriting parts, so to
can your code be made better by refactoring parts of it.
• Refactoring refers to improving your code style without
altering its behavior.
• Refactoring is one of the most powerful techniques for
producing good code.
• Reasons to refactor:
– Duplicated code
– Excessively large or long functions
– Etc.
Image Credit: publicdomainvectors.org
What Do You Do When You
Refactor?
• Turn a code fragment in to a standalone function
with its own name and calls to it.
• Replace the body of a function with a new algorithm
that is clearer and which returns the same results.
• Move an algorithm from one function to another
where it makes more sense
• Divide a function into two functions.
Image Credit: publicdomainvectors.org
User Problem Arrival Rate
• When software is released, there is usually a surge in customer questions
and support requests.
• Initially customers find all of the easy to find bugs.
• Expect problem reports to decrease over time
• If you don’t see a surge in issues, then there is a good chance the your
customers are not using the software that you just delivered to them.
Process For Fixing A
Customer Problem
• The problem description, priority, and other important information is
recorded in a problem report that is submitted to the technical fix group.
• The technical fix group will attempt to reproduce the problem.
• The technical fix group will then either accept or reject the problem.
• If the problem is rejected, the customer support team is immediately
notified; if it is accepted, then a change request is generated and it enters
the code change cycle.
• Depending on priority, a new code version may be created or the fix will
be scheduled to be part of a future release.
• The FAQ database is updated with information on this issue
Image Credit: www.innoforce.com
An Introduction To
Software Development
Using Python
Spring Semester, 2015
Class #26:
Final Exam Review
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
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
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
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
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
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
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
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…
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
Spaghetti Code Example
• Instead, add another task that sets the
shipping cost to $10
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
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
Boolean Truth Table
Image Credit: www.clipartpanda.com
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
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.
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.
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
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
Send The Result Back
• In order to return the result of the function,
use the return statement:
return selection
Image Credit: www.clipartpanda.com
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
Definition Of A Function
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
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
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
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
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
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
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
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
Opening / Closing Files Syntax
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
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
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
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
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
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
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
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”
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
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
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
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
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
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
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
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
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
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
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”}
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
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
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
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
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
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
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
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
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
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
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
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
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
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
What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
DictionaryLists And/Or/Not Functions Files ExceptionSets Modules

More Related Content

What's hot

30 of the best free software test tools in 60 minutes by Jess Lancaster
30 of the best free software test tools in 60 minutes by Jess Lancaster30 of the best free software test tools in 60 minutes by Jess Lancaster
30 of the best free software test tools in 60 minutes by Jess Lancaster
QA or the Highway
 
Heuristics, mnemonics and other Greek words in the exploratory testing of mob...
Heuristics, mnemonics and other Greek words in the exploratory testing of mob...Heuristics, mnemonics and other Greek words in the exploratory testing of mob...
Heuristics, mnemonics and other Greek words in the exploratory testing of mob...
COMAQA.BY
 

What's hot (20)

Improving Test Team Throughput via Architecture by Dustin Williams
Improving Test Team Throughput via Architecture by Dustin WilliamsImproving Test Team Throughput via Architecture by Dustin Williams
Improving Test Team Throughput via Architecture by Dustin Williams
 
Continuous everything
Continuous everythingContinuous everything
Continuous everything
 
Lessons Learned in Test Automation From Zombieland
Lessons Learned in Test Automation From ZombielandLessons Learned in Test Automation From Zombieland
Lessons Learned in Test Automation From Zombieland
 
30 of the best free software test tools in 60 minutes by Jess Lancaster
30 of the best free software test tools in 60 minutes by Jess Lancaster30 of the best free software test tools in 60 minutes by Jess Lancaster
30 of the best free software test tools in 60 minutes by Jess Lancaster
 
Automation Testing Project and Framework Details
Automation Testing Project and Framework DetailsAutomation Testing Project and Framework Details
Automation Testing Project and Framework Details
 
Myth vs Reality: Understanding AI/ML for QA Automation - w/ Jonathan Lipps
Myth vs Reality: Understanding AI/ML for QA Automation - w/ Jonathan LippsMyth vs Reality: Understanding AI/ML for QA Automation - w/ Jonathan Lipps
Myth vs Reality: Understanding AI/ML for QA Automation - w/ Jonathan Lipps
 
Continuous Integration: Finding problems soonest
Continuous Integration: Finding problems soonestContinuous Integration: Finding problems soonest
Continuous Integration: Finding problems soonest
 
QAorHighway2016
QAorHighway2016QAorHighway2016
QAorHighway2016
 
Inside Behavior Driven Development
Inside Behavior Driven DevelopmentInside Behavior Driven Development
Inside Behavior Driven Development
 
TDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and JasmineTDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and Jasmine
 
Leandro Melendez - Switching Performance Left & Right
Leandro Melendez - Switching Performance Left & RightLeandro Melendez - Switching Performance Left & Right
Leandro Melendez - Switching Performance Left & Right
 
The Art of Gherkin Scripting - Matt Eakin
The Art of Gherkin Scripting - Matt EakinThe Art of Gherkin Scripting - Matt Eakin
The Art of Gherkin Scripting - Matt Eakin
 
Growing Manual Testers into Automators
Growing Manual Testers into AutomatorsGrowing Manual Testers into Automators
Growing Manual Testers into Automators
 
Jonathon Wright - Intelligent Performance Cognitive Learning (AIOps)
Jonathon Wright - Intelligent Performance Cognitive Learning (AIOps)Jonathon Wright - Intelligent Performance Cognitive Learning (AIOps)
Jonathon Wright - Intelligent Performance Cognitive Learning (AIOps)
 
The Art of Giving and Receiving Code Reviews
The Art of Giving and Receiving Code ReviewsThe Art of Giving and Receiving Code Reviews
The Art of Giving and Receiving Code Reviews
 
Heuristics, mnemonics and other Greek words in the exploratory testing of mob...
Heuristics, mnemonics and other Greek words in the exploratory testing of mob...Heuristics, mnemonics and other Greek words in the exploratory testing of mob...
Heuristics, mnemonics and other Greek words in the exploratory testing of mob...
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Forget Quality!
Forget Quality!Forget Quality!
Forget Quality!
 
I Don't Test Often ...
I Don't Test Often ...I Don't Test Often ...
I Don't Test Often ...
 
Build FAST with parallel_calabash
Build FAST with parallel_calabashBuild FAST with parallel_calabash
Build FAST with parallel_calabash
 

Viewers also liked

Viewers also liked (8)

An Introduction To Python - Functions, Part 1
An Introduction To Python - Functions, Part 1An Introduction To Python - Functions, Part 1
An Introduction To Python - Functions, Part 1
 
An Introduction To Python - FOR Loop
An Introduction To Python - FOR LoopAn Introduction To Python - FOR Loop
An Introduction To Python - FOR Loop
 
An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()
 
An Introduction To Python - Problem Solving: Flowcharts & Test Cases, Boolean...
An Introduction To Python - Problem Solving: Flowcharts & Test Cases, Boolean...An Introduction To Python - Problem Solving: Flowcharts & Test Cases, Boolean...
An Introduction To Python - Problem Solving: Flowcharts & Test Cases, Boolean...
 
An Introduction To Python - Modules & Solving Real World Problems
An Introduction To Python - Modules & Solving Real World ProblemsAn Introduction To Python - Modules & Solving Real World Problems
An Introduction To Python - Modules & Solving Real World Problems
 
An Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewAn Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam Review
 
An Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm Review
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
 

Similar to An Introduction To Software Development - Final Review

Introduction to-automated-testing
Introduction to-automated-testingIntroduction to-automated-testing
Introduction to-automated-testing
BestBrains
 
Becoming a better programmer - unit testing
Becoming a better programmer - unit testingBecoming a better programmer - unit testing
Becoming a better programmer - unit testing
Duy Tan Geek
 

Similar to An Introduction To Software Development - Final Review (20)

An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
 
An Introduction To Software Development - Test Driven Development
An Introduction To Software Development - Test Driven DevelopmentAn Introduction To Software Development - Test Driven Development
An Introduction To Software Development - Test Driven Development
 
SauceCon 2017: Making Your Mobile App Automatable
SauceCon 2017: Making Your Mobile App AutomatableSauceCon 2017: Making Your Mobile App Automatable
SauceCon 2017: Making Your Mobile App Automatable
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven Development
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
 
Introduction to-automated-testing
Introduction to-automated-testingIntroduction to-automated-testing
Introduction to-automated-testing
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
 
Agile Development | Agile Process Models
Agile Development | Agile Process ModelsAgile Development | Agile Process Models
Agile Development | Agile Process Models
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Agile Acceptance testing with Fitnesse
Agile Acceptance testing with FitnesseAgile Acceptance testing with Fitnesse
Agile Acceptance testing with Fitnesse
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
Code Reviews
Code ReviewsCode Reviews
Code Reviews
 
Becoming a better programmer - unit testing
Becoming a better programmer - unit testingBecoming a better programmer - unit testing
Becoming a better programmer - unit testing
 
How to scale your Test Automation
How to scale your Test AutomationHow to scale your Test Automation
How to scale your Test Automation
 
Topic production code
Topic production codeTopic production code
Topic production code
 
Lecture3.se.pptx
Lecture3.se.pptxLecture3.se.pptx
Lecture3.se.pptx
 
Backward thinking design qa system for quality goals
Backward thinking   design qa system for quality goalsBackward thinking   design qa system for quality goals
Backward thinking design qa system for quality goals
 

Recently uploaded

Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 

Recently uploaded (20)

The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 

An Introduction To Software Development - Final Review

  • 1. An Introduction To Software Development Using Python Spring Semester, 2015 Class #27: Final Exam Review
  • 2. Welcome To TDD! • When you are creating test cases before you write code and then letting those test cases drive how you create your code, you are using Test Driven Development (TDD). • TDD is a formal term that is used to describe the process of testing from the outset of development. • This means that you write every line of code specifically as a response to your tests. Image Credit: revistanautilus.ro
  • 3. TDD Rule #1 • TDD Rule #1: Your test should always fail before you implement any code. • You want your tests to fail when you first write them. • The point of the test is to establish a measurable success. • Because your test is failing, now it’s clear what you have to do to make sure that test passes. Image Credit: www.fs.usda.gov
  • 4. 3 Steps To Test Driven Development • Red: Your Test Fails – Write a test to check whatever functionality you are going to write. – It will fail because you have not yet implemented that functionality. – This is the red stage because your testing GUI will show the test in red (failing). • Green: Your Test Passes – Implement the functionality to get that test to pass – Write the simplest code possible to get the test to pass. – This is the green stage. • Refactor: Clean up – duplication, ugly code, old code, etc. – After your test passes, go back in and clean up things that you noticed while implementing your code. – This is the refactor stage. – Next, go on to create the next test. Pay with Visa 3 Pay with Visa / MC / Paypal Image Credit: cliparts.co
  • 5. What Does Testing First Buy Us? • Testing produces better code • Create well-organized code – Simpler code – Nothing that is not absolutely required • Code that always does the same thing – Production code does the same thing as testing code – We are writing production code all the time • Code is loosely coupled – Tightly coupled code is brittle and breaks easily – Our code will be broken into a loosely coupled flexible system Image Credit: www.fotosearch.com
  • 6. System Testing • Have to use the system in order to ensure that it works. – Dedicated end-to-end system testing period – Let the real users work on the system • Test the system in a situation that is as close to real- world as is possible. • System testing is all about reality – the system as a whole, not the individual parts. Image Credit: cpsobsessed.com
  • 7. Why Do System Testing? • Unit testing is a great way to make sure that your specific piece of code works. • Unit testing can miss the bugs that only show up when different pieces of code are hooked together or when real users start to use the system. • System testing hooks everything together and treats the system like a black box. The goal is to test the functionality that the user expects. System testing exercises the functionality of the system from front-to-back using real-world, black box scenarios. Image Credit: joyin6th.blogspot.com
  • 8. Good System Testing Requires Two Iteration Cycles • Iterations allow the development team to stay focused • Provide checkpoints with customers • You need the same things for good system testing • How about having two cycles of iteration going at the same time? Iteration 1 Iteration 2 Iteration 3 Fix Bugs Prep for IT 1 Test It. 1 Build Test It. 2 Build Test It. 3 Build Test team signs off on working version
  • 9. How To Deal With BUGS! A tester finds a bug • Could be a fail • Poor documentation • Missing feature Tester files a bug report • Track bugs! • Level of detail is critical • What were you trying to do? • Error messages? • Steps to recreate • Expected outcome Create a story / task to fix the bug • Create bug fix story • Add tasks as needed • Tough to estimate Image Credit: www.publicdomainpictures.net
  • 10. How To Deal With BUGS! Fix the bug • Part of an iteration • Create the test first • Mark bug as fixed on bug tracker • Don’t mark as tested / closed / or verified. Check the fix • Tester / original reporter tests the change • Now bug can be marked as “closed” Update bug report • Close the bug report • Use report as a script for retest • Do not delete it – you may need to refer back to it Image Credit: www.dreamstime.com
  • 11. Why Create A Bug Report? • A “bug” is an issue that you HAVE to address • Bugs have to be recorded and tracked • Popular free bug tracking program: Bugzilla • Use your bug tracker to do the following: – Record and communicate bug priorities – Keep track of everything – Generate metrics Image Credit: vector.me
  • 12. The Software Development Process • A good software process is all about prioritization. • Make sure that you are doing the right thing on the project at all times. • Goal: produce working code. Second goal: produce quality code • Always be improving your process Image Credit: www.clipartof.com
  • 13. 3 Things That Make Working Software • Completing an iteration’s scheduled work – Burn down rate indicates how well your iteration went – If you didn’t end on time, but got work done and the customer is happy then it was all good • Passing all of the tests – Unit tests, system tests, black / white box tests • Satisfying your customer Image Credit: www.clipartlord.com, www.clipartpanda.com
  • 14. Things To Do At The Start Of A New Iteration • Revise both story and task estimates – You now have more knowledge about how things will work – Revisit estimates for remaining user stories and associated tasks • Revise velocity – Probably used an initial value of 0.7 (30% wasted) – Use hard data to recalculate new velocity – Goal is to provide customer with confident statements • Recalculate your estimates and velocity at the start of every iteration, applying what you learned from the previous iteration Image Credit: www.fotosearch.com
  • 15. Change Causes 3 Things To Have To Be Updated • User Stories – Every change to the code has to be documented by a user story – In this case, the customer’s ability to post a review of their stay needs to have a user story created for it • Estimates – Every user story needs an estimate – How much time will it take to code that function? – How much time will it take to integrate that function with other code? • Priorities – The customer has to assign a priority to each user story – You then need to plan out the work for the next iteration Image Credit: www.fotosearch.com
  • 16. What To Do When Bugs Are Discovered • Software bugs are going to have an impact on your iteration schedule – they have to be fixed • Talk with the team – if the bug’s impact is going to be significant (functionality / schedule) then you are going to have to talk with your customer. • You’ll need to have an estimate as to when you can have this bug fixed. Image Credit: www.clipartpanda.com
  • 17. Spike Testing • Spike Testing: doing one burst of activity, observing what you accomplish, using that to estimate how much time it will take to get everything done. • One possible spike testing plan: – Take one week to conduct your spike test – Pick a random sample to fix from the tests that are failing – At the end of the week calculate your bug fix rate: Bugs Fixed 5 = your daily bug fix rate Image Credit: states.phillipmartin.info
  • 18. What Will Your Spike Test Results Reveal? • Test cases revealed how much of your code was failing. Your spike tests should reveal how long it is going to take you to fix your bugs. • Example: 4 5 Total # bugs How long will it take to fix all bugs? Bug fix rate x # of bugs = # days required to fix all bugs 0.8 x (13-4) = 7 days Bugs fixed during spike testing Image Credit: www.dreamstime.com
  • 19. Functional Decomposition • Decompose a function or a module into smaller modules, which will be composed together to form the bigger module. • Example: College course registration & enrollment • Four tasks need to be done: – Modify and delete students from the database – Modify and delete courses from the database – Add, modify, and delete sections for a given course – Register and drop students from a section
  • 20. Modular Decomposition For Student Registration System Numbering is used to keep track of the parents of modules.
  • 21. What Makes A Good Implementation? • Readability – can be easily read an understood by other programmers • Maintainability – code can be easily modified and maintained • Performance – the code should run as fast as possible • Traceability – all code needs to be able to be traced back to a user story • Correctness – the code needs to do what it is supposed to do • Completeness – all system requirements must be met Note that each of these requires a trade off. Performance optimization may decrease the code’s readability and maintainability… Image Credit: www.dreamstime.com
  • 22. Comments • Comments are important • Comments can help or hurt program readability and maintainability. • Two main problem with comments: – They may distract from the code and make a section more difficult to read – They may be wrong • Comments may become outdated as the code changes. • Comments may be wrong from the start because they are never executed/tested. Image Credit: www.clipartpanda.com
  • 23. Comments Are A Trade-Off • We need to recognize the trade-off that comments represent. • Comments can help to clarify code and relate it to other sources. • They also represent some level of duplication of the code. • It takes time to both create them and then to maintain them. • Comment errors can be very hard to both find and correct. Image Credit: www.fotosearch.com
  • 24. Comment Dangers! • Comments can be used to justify bad coding practices • Programmers may be tempted to create code that is too complicated or too hard to maintain and then add comments to it instead of rewriting it to better coding standards. • An alternative: code that is so well written that it documents itself (“self documenting code”). • Good goal, but comments still have a place in capturing the programmer’s intent. Image Credit: www.clipartof.com
  • 25. Debugging • Debugging is all about locating and fixing errors in the code. • Generally errors are found by testing, but they can also be reported by users or code inspections. • Debugging is a highly iterative process. Image Credit: www.clker.com
  • 26. Performance Optimization • Performance for any program is important, but… • Optimizing for performance almost always affects code maintainability and readability for the worse. • Real-time systems are the exception – they are all about performance. • Programmers often make the mistake of worrying about performance too early in the development cycle. – Get the code to work first and make it easy to maintain – If the performance is unsatisfactory, then you can optimize performance – most times this won’t be an issue. – Most code is only executed a few times and does not impact performance – Only a few pieces of code will have to be optimized for performance Image Credit: www.istockphoto.com
  • 27. How To Optimize Performance • Start with a profiler tool – Runs the program and calculates how much time is spent in each part. – Helps you to find bottlenecks and to determine what code needs to be optimized • Now review and optimize only those modules that will have an impact on performance • After making changes, run the profiler again to determine impact and to ensure changes actually boosted performance. Image Credit: www.dreamstime.com
  • 28. The Cost Of Optimization • A cost / benefit analysis should be done before performing any performance optimization. • A programmer’s time is more expensive than computer time – it may be cheaper to just buy faster hardware. • You need to weigh the increase in performance against the decrease in maintainability and the possibility of introducing errors. Image Credit: www.clipartpanda.com
  • 29. Refactoring • Just like a novel can be made better by rewriting parts, so to can your code be made better by refactoring parts of it. • Refactoring refers to improving your code style without altering its behavior. • Refactoring is one of the most powerful techniques for producing good code. • Reasons to refactor: – Duplicated code – Excessively large or long functions – Etc. Image Credit: publicdomainvectors.org
  • 30. What Do You Do When You Refactor? • Turn a code fragment in to a standalone function with its own name and calls to it. • Replace the body of a function with a new algorithm that is clearer and which returns the same results. • Move an algorithm from one function to another where it makes more sense • Divide a function into two functions. Image Credit: publicdomainvectors.org
  • 31. User Problem Arrival Rate • When software is released, there is usually a surge in customer questions and support requests. • Initially customers find all of the easy to find bugs. • Expect problem reports to decrease over time • If you don’t see a surge in issues, then there is a good chance the your customers are not using the software that you just delivered to them.
  • 32. Process For Fixing A Customer Problem • The problem description, priority, and other important information is recorded in a problem report that is submitted to the technical fix group. • The technical fix group will attempt to reproduce the problem. • The technical fix group will then either accept or reject the problem. • If the problem is rejected, the customer support team is immediately notified; if it is accepted, then a change request is generated and it enters the code change cycle. • Depending on priority, a new code version may be created or the fix will be scheduled to be part of a future release. • The FAQ database is updated with information on this issue Image Credit: www.innoforce.com
  • 33. An Introduction To Software Development Using Python Spring Semester, 2015 Class #26: Final Exam Review
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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…
  • 42. 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
  • 43. Spaghetti Code Example • Instead, add another task that sets the shipping cost to $10
  • 44. 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
  • 45. 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
  • 46. Boolean Truth Table Image Credit: www.clipartpanda.com
  • 47. 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
  • 48. 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.
  • 49. 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.
  • 50. 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
  • 51. 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
  • 52. Send The Result Back • In order to return the result of the function, use the return statement: return selection Image Credit: www.clipartpanda.com
  • 53. 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
  • 54. Definition Of A Function
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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
  • 63. Opening / Closing Files Syntax
  • 64. 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
  • 65. 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
  • 66. 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
  • 67. 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
  • 68. 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
  • 69. 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
  • 70. 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
  • 71. 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”
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 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
  • 76. 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
  • 77. 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
  • 78. 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
  • 79. 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
  • 80. 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
  • 81. 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
  • 82. 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”}
  • 83. 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
  • 84. 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
  • 85. 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
  • 86. 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
  • 87. 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
  • 88. 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
  • 89. 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
  • 90. 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
  • 91. 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
  • 92. 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
  • 93. 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
  • 94. 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
  • 95. 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
  • 96. 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
  • 97. What’s In Your Python Toolbox? print() math strings I/O IF/Else elif While For DictionaryLists And/Or/Not Functions Files ExceptionSets Modules