An Introduction To Software Development - Final Review

97
An Introduction To Software Development Using Python Spring Semester, 2015 Class #27: Final Exam Review

Transcript of An Introduction To Software Development - Final Review

Page 1: An Introduction To Software Development - Final Review

An Introduction To

Software Development

Using Python

Spring Semester, 2015

Class #27:

Final Exam Review

Page 2: An Introduction To Software Development - Final 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

Page 3: An Introduction To Software Development - Final Review

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

Page 4: An Introduction To Software Development - Final Review

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

Page 5: An Introduction To Software Development - Final Review

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

Page 6: An Introduction To Software Development - Final Review

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

Page 7: An Introduction To Software Development - Final Review

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

Page 8: An Introduction To Software Development - Final Review

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

Page 9: An Introduction To Software Development - Final Review

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

Page 10: An Introduction To Software Development - Final Review

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

Page 11: An Introduction To Software Development - Final Review

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

Page 12: An Introduction To Software Development - Final Review

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

Page 13: An Introduction To Software Development - Final Review

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

Page 14: An Introduction To Software Development - Final Review

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

Page 15: An Introduction To Software Development - Final Review

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

Page 16: An Introduction To Software Development - Final Review

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

Page 17: An Introduction To Software Development - Final Review

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

Page 18: An Introduction To Software Development - Final Review

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

Page 19: An Introduction To Software Development - Final Review

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

Page 20: An Introduction To Software Development - Final Review

Modular Decomposition For

Student Registration System

Numbering is used to keep track

of the parents of modules.

Page 21: An Introduction To Software Development - Final Review

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

Page 22: An Introduction To Software Development - Final Review

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

Page 23: An Introduction To Software Development - Final Review

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

Page 24: An Introduction To Software Development - Final Review

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

Page 25: An Introduction To Software Development - Final Review

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

Page 26: An Introduction To Software Development - Final Review

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

Page 27: An Introduction To Software Development - Final Review

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

Page 28: An Introduction To Software Development - Final Review

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

Page 29: An Introduction To Software Development - Final Review

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

Page 30: An Introduction To Software Development - Final Review

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

Page 31: An Introduction To Software Development - Final Review

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.

Page 32: An Introduction To Software Development - Final Review

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

Page 33: An Introduction To Software Development - Final Review

An Introduction To

Software Development

Using Python

Spring Semester, 2015

Class #26:

Final Exam Review

Page 34: An Introduction To Software Development - Final 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 Programmi ng” 3

“COP 2271c”, “Introduction to Computation and Programm ing”, 3

[“COP 2271c”, “Introduction to Computation and Program ming”, 3]

prerequisites = [“COP 2271c”, “Introduction to Computa tion and Programming”, 3]

COP 2271c Introduction to Computation and Programmi ng 3

Image Credit: Clipart Panda

Page 35: An Introduction To Software Development - Final Review

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

Page 36: An Introduction To Software Development - Final Review

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

Page 37: An Introduction To Software Development - Final Review

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

Page 38: An Introduction To Software Development - Final Review

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

Page 39: An Introduction To Software Development - Final Review

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

Page 40: An Introduction To Software Development - Final Review

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

Page 41: An Introduction To Software Development - Final Review

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…

Page 42: An Introduction To Software Development - Final Review

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

Page 43: An Introduction To Software Development - Final Review

Spaghetti Code Example

• Instead, add another task that sets the

shipping cost to $10

Page 44: An Introduction To Software Development - Final Review

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

Page 45: An Introduction To Software Development - Final Review

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

Page 46: An Introduction To Software Development - Final Review

Boolean Truth Table

Image Credit: www.clipartpanda.com

Page 47: An Introduction To Software Development - Final Review

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

Page 48: An Introduction To Software Development - Final Review

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.

Page 49: An Introduction To Software Development - Final Review

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.

Page 50: An Introduction To Software Development - Final Review

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

Page 51: An Introduction To Software Development - Final Review

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

Page 52: An Introduction To Software Development - Final Review

Send The Result Back

• In order to return the result of the function,

use the return statement:

return selection

Image Credit: www.clipartpanda.com

Page 53: An Introduction To Software Development - Final Review

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

Page 54: An Introduction To Software Development - Final Review

Definition Of A Function

Page 55: An Introduction To Software Development - Final Review

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

Page 56: An Introduction To Software Development - Final Review

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

Page 57: An Introduction To Software Development - Final Review

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

Page 58: An Introduction To Software Development - Final Review

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

Page 59: An Introduction To Software Development - Final Review

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

Page 60: An Introduction To Software Development - Final Review

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

Page 61: An Introduction To Software Development - Final Review

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

Page 62: An Introduction To Software Development - Final Review

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

Page 63: An Introduction To Software Development - Final Review

Opening / Closing Files Syntax

Page 64: An Introduction To Software Development - Final Review

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

Page 65: An Introduction To Software Development - Final Review

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 "flying\n".

• 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 "circus\n".

• Calling readline again yields the empty string "" because you have reached

the end of the file. Image Credit: fanart.tv

Page 66: An Introduction To Software Development - Final Review

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

Page 67: An Introduction To Software Development - Final Review

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

Page 68: An Introduction To Software Development - Final Review

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: %d\nTotal: %8.2f\n" %

(count, total))

Image Credit: www.freeclipartnow.com

Page 69: An Introduction To Software Development - Final Review

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

Page 70: An Introduction To Software Development - Final Review

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

Page 71: An Introduction To Software Development - Final Review

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”

Page 72: An Introduction To Software Development - Final Review

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

Page 73: An Introduction To Software Development - Final Review

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

Page 74: An Introduction To Software Development - Final Review

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

Page 75: An Introduction To Software Development - Final Review

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

Page 76: An Introduction To Software Development - Final Review

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

Page 77: An Introduction To Software Development - Final Review

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

Page 78: An Introduction To Software Development - Final Review

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

Page 79: An Introduction To Software Development - Final Review

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

Page 80: An Introduction To Software Development - Final Review

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

Page 81: An Introduction To Software Development - Final Review

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

Page 82: An Introduction To Software Development - Final Review

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”}

Page 83: An Introduction To Software Development - Final Review

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

Page 84: An Introduction To Software Development - Final Review

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

Page 85: An Introduction To Software Development - Final Review

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

Page 86: An Introduction To Software Development - Final Review

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

Page 87: An Introduction To Software Development - Final Review

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

Page 88: An Introduction To Software Development - Final Review

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

Page 89: An Introduction To Software Development - Final Review

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

Page 90: An Introduction To Software Development - Final Review

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

Page 91: An Introduction To Software Development - Final Review

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

Page 92: An Introduction To Software Development - Final Review

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

Page 93: An Introduction To Software Development - Final Review

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.com main-1

Page 94: An Introduction To Software Development - Final Review

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

Page 95: An Introduction To Software Development - Final Review

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

Page 96: An Introduction To Software Development - Final Review

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

Page 97: An Introduction To Software Development - Final Review

What’s In Your Python Toolbox?

print() math strings I/O IF/Else elif While For

Dictionary Lists And/Or/Not Functions Files Exception Sets Modules