an introduction to python - python midterm review

58
An Introduction To Software Development Using Python Spring Semester, 2015 Midterm Review

Upload: blue-elephant-consulting

Post on 16-Jul-2015

430 views

Category:

Education


4 download

TRANSCRIPT

Page 1: An Introduction To Python - Python Midterm Review

An Introduction To Software

Development Using Python

Spring Semester, 2015

Midterm Review

Page 2: An Introduction To Python - Python Midterm Review

What’s In Your Python Toolbox?

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

Lists

Page 3: An Introduction To Python - Python Midterm Review

A Closer Look At Our First Program

• # My first Python program.– This is a comment – it’s for you, not the computer

– Comments begin with # and are not statements.

• print("Hello, World!")– displays a line of text, namely “Hello, World!”.

– We call a function named print and pass it the information to be displayed.

– A function is a collection of programming instructions that carry out a particular task.

– It is part of the Python language.

Page 4: An Introduction To Python - Python Midterm Review

Print Function Syntax

Page 5: An Introduction To Python - Python Midterm Review

Let’s Talk About Variables…• Variables are reserved memory locations to store values. This means that

when you create a variable you reserve some space in memory.

• Variables in Python consist of an alphanumeric name beginning in a letter or underscore. Variable names are case sensitive.

• Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

• The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

• Examples:counter = 100 miles = 1000.0name = "John"

Image Credit: ClipArt Best

Python variablenames can have unlimited length –but keep them short!

Page 6: An Introduction To Python - Python Midterm Review

Let’s Talk About Python Math!

Normal Stuff

Weird Stuff5%2 = 1

Page 7: An Introduction To Python - Python Midterm Review

Modulo (%) Is Your Friend

• A man has 113 cans of Coke. He also has a group of boxes that can hold 12 cans each. How many cans will he have left over once he’s loaded all of the boxes?

• On a military base the clock on the wall says that the time is 23:00. What time of day is this?

• My friend has 10,432 ping pong balls that he needs to put into storage. My car can transport 7,239 balls. How many will be left after I leave?

Page 8: An Introduction To Python - Python Midterm Review

What Comes First? Precedence Rules

• The precedence rules you learned in algebra apply during the evaluation of arithmetic expressions in Python:

– Exponentiation has the highest precedence and is evaluated first.

– Unary negation is evaluated next, before multiplication, division, andremainder.

– Multiplication, division, and remainder are evaluated before addition andsubtraction.

– Addition and subtraction are evaluated before assignment.

– With two exceptions, operations of equal precedence are left associative,so they are evaluated from left to right. Exponentiation and assignmentoperations are right associative, so consecutive instances of these are evaluated from right to left.

– You can use parentheses to change the order of evaluation

• "PEMDAS", which is turned into the phrase "Please Excuse My Dear Aunt Sally". It stands for "Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction".

3**2

-5

2+3*4/6sum = 2+3

2+3*4/6

sum = 3**2**5(2+3)*4/5

Image Credit: www.pinterest.com

Page 9: An Introduction To Python - Python Midterm Review

Precedence Rules: Examples

• Simplify 4 + 32

• Simplify 4 + (2 + 1)2

• Simplify 4 + [–1(–2 – 1)]2

• Simplify 4( –2/3 + 4/3)• Three people ate dinner at a restaurant and want to split the

bill. The total is $35.27, and they want to leave a 15 percent tip. How much should each person pay?

Image Credit: pixgood.com

Page 10: An Introduction To Python - Python Midterm Review

Not All Numbers Are Created Equal

• Integers are the numbers you can easily count, like 1, 2, 3, as well as 0 and the negative numbers, like –1, –2, –3.

• Decimal numbers (also called real numbers) are the numbers with a decimal point and some digits after it, like 1.25, 0.3752, and –101.2.

• In computer programming, decimal numbers are also called floating-point numbers, or sometimes floats for short (or float for just one of them). This is because the decimal point “floats” around. You can have the number 0.00123456 or 12345.6 in a float.

Image Credit: www.clipartpanda.com

Page 11: An Introduction To Python - Python Midterm Review

Mixed-Mode Arithmetic and Type Conversions

• Performing calculations involving both integers and floating-point numbers is called mixed-mode arithmetic.

• Conversions

– Determine type: type()

– Drop decimal: int()

– Round up / down: round()

– Change to decimal: float()

– Change to string: str()

Image Credit: personaltrainerbusinesssystems.com

Page 12: An Introduction To Python - Python Midterm Review

Cool Kid Stuff: Increment / Decrement / E-Notation

• Incrementing: sum = sum + 1

– sum += 1

• Decrementing: sum = sum – 1

– sum -= 1

• E-Notation

– 1,000,000 = 1 x 10**6 = 1e6

Image Credit: www.toonvectors.com

Page 13: An Introduction To Python - Python Midterm Review

Say Hello To Strings!

• Your computer programs will have to process text in addition to numbers.

• Text consists of characters: letters, numbers, punctuation, spaces, and so on.

• A string is a sequence of characters.

• Example: “John Smith”

Image Credit: imgarcade.com

Page 14: An Introduction To Python - Python Midterm Review

How Do We Deal With Strings?

• Strings can be stored in variables: answer = “a”

• A string literal denotes a particular string:“Mississippi”

• In Python, string literals are specified by enclosing a sequence of characters within a matching pair of either single or double quotes.

“fire truck” or ‘fire truck’

Image Credit: imgarcade.com

Page 15: An Introduction To Python - Python Midterm Review

Strings and Characters

• Strings are sequences of Unicode characters.

• You can access the individual characters of a string based on their position within the string.

• This position is called the index of the character.

Image Credit: www.fontspace.com

0 1 2 3 4

First Last

Page 16: An Introduction To Python - Python Midterm Review

String Indexes

• name = “TILEZ”

• len(name) = 5

• name[0] = “T”, name[4] = “Z”

0 1 2 3 4

Page 17: An Introduction To Python - Python Midterm Review

All Characters Have Numbers

• A character is stored internally as an integer value. The specific value used for a given characteris based on its ASCII code (or Unicode code).

• Python provides two functions related to character encodings. – The ord function returns the number used to represent a given

character. ord(“A”) = 65

– The chr function returns the character associatedwith a given code. chr(65) = “A”

Image Credit: www.clipartpanda.com

Page 18: An Introduction To Python - Python Midterm Review

Input and Output

• When a program asks for user input, it should first print a message that tells the user which input is expected. Such a message is called a prompt. In Python, displaying a prompt and reading the keyboard input is combined in one operation.– first = input("Enter your first name: ")

• The input function displays the string argument in the console window and places the cursor on the same line, immediately following the string.– Enter your first name: █

Image Credit: blogs.msdn.com

Page 19: An Introduction To Python - Python Midterm Review

Numerical Input

• The input function can only obtain a string of text from the user.

• To read an integer value, first use the input function to obtain the data as a string, then convert it to an integer using the intfunction.

numBottles = input("Please enter the number of bottles: ")bottles = int(numBottles)

bottlePrice = input("Enter price per bottle: ")price = float(bottlePrice)

Image Credit: www.canstockphoto.com

Page 20: An Introduction To Python - Python Midterm Review

Formatted Output

• To control how your output looks, you print a formatted string and then provide the values that are to be “plugged in”.

• If the value on the right of the “%” is a string, then the % symbol becomes the string format operator.

• The construct %10.2f is called a format specifier: it describes how a value should be formatted. – The 10 specifies the size of the field, the 2 specified the number of digits after the “.”.

– The letter f at the end of the format specifier indicates that we are formatting a floating-point value. Use d for an integer value and s for a string;

Page 21: An Introduction To Python - Python Midterm Review

Formatted Output

• To specify left justification for a string, add a minus sign before the string field width:

title1 = "Quantity:“title2 = "Price:"print("%-10s %10d" % (title1, 24))print("%-10s %10.2f" % (title2, 17.29))

• The result is:Quantity: 24Price: 17.29

Image Credit: www.theindianrepublic.com

Page 22: An Introduction To Python - Python Midterm Review

Python Format Specifier Examples

Page 23: An Introduction To Python - Python Midterm Review

Say Hello To The “IF” Statement

• In Python, an IF statement is used to implement a decision.

• When a condition is fulfilled, one set of statements is executed. Otherwise, another set of statements is executed

Image Credit: www.clipartpanda.com

Page 24: An Introduction To Python - Python Midterm Review

Syntax Of Python IF Statement

Page 25: An Introduction To Python - Python Midterm Review

Tabs

• Blockstructured code has the property that nested statements are indented by one or more levels:

if totalSales > 100.0 :

discount = totalSales * 0.05

totalSales = totalSales − discount

print("You received a discount of $%.2f" % discount)

else :

diff = 100.0 − totalSales

if diff < 10.0 :

print("purchase our item of the day & you can receive a 5% discount.")

else :

print("You need to spend $%.2f more to receive a 5% discount." % diff)

Image Credit: www.clipartpanda.com

Page 26: An Introduction To Python - Python Midterm Review

Relational Operators

EqualityTestingRequires2 “=“

Note: relational operators have a lower precedence than arithmetic operators

Page 27: An Introduction To Python - Python Midterm Review

Examples Of Relational Operators

Page 28: An Introduction To Python - Python Midterm Review

What Is A “Nested Branch”?

• It is often necessary to include an if statement inside another. Such an arrangement is called a nested set of statements.

• Example:

Is the club full?

Arrive atthe club

Are you on the

VIP list?

Wait in car

Go right in

Wait in lineY

Y

N

N

Page 29: An Introduction To Python - Python Midterm Review

Example of a “Nested Branch”

if (peopleInClub < maxPeopleInClub) :

if (youName == VIPListName) :

goRightIn

else :

waitInLine

else :

waitInCar

Page 30: An Introduction To Python - Python Midterm Review

Problems With “Super Nesting”

• Difficult to read

• Shifted too far to the right due to indentation

Image Credit: www.clipartbest.com

Page 31: An Introduction To Python - Python Midterm Review

A Better Way: elif

If (classScore >=90) :print(“You got an A!”)

elif (classScore >= 80) :print(“You did ok, you got a B!”)

elif (classScore >=70) :print(“So-so, you got a C”)

elif (classScore >= 60) :print(“Oh –oh, you got a D”)

else :print(“Dang it, you got an F”)

Image Credit: jghue.blogspot.com

Note that you have to test the more specific conditions first.

Page 32: An Introduction To Python - Python Midterm Review

How Do You Do Things Over And Over Again?

• In Python, loop statements repeatedly execute instructions until a goal has been reached.

• In Python, the while statement implements such a repetition. It has the form:

while condition : statement1statement 2

• As long as the condition remains true, the statements inside the while statement are executed.

Image Credit: etc.usf.edu

Body

Condition

Page 33: An Introduction To Python - Python Midterm Review

How Can I Loop For A Given Number Of Times?

• You can use a while loop that is controlled by a counter:

counter = 1 # Initialize the counter.while counter <= 10 : # Check the counter.

print(counter)counter = counter + 1 # Update the loop variable

Note: Some people call this loop count-controlled.

Image Credit: www.dreamstime.com

Page 34: An Introduction To Python - Python Midterm Review

The For Statement

The for loop can be used to iterate over the contents of any container, which is anobject that contains or stores a collection of elements. Thus, a string is a containerthat stores the collection of characters in the string.

Page 35: An Introduction To Python - Python Midterm Review

What’s The Difference Between While Loops and For Loops?

• In the for loop, the element variable is assigned stateName[0] , stateName[1] , and so on.

• In the while loop, the index variable i is assigned 0, 1, and so on.

Image Credit: www.clipartpanda.com

Page 36: An Introduction To Python - Python Midterm Review

The Range Function

• Count-controlled loops that iterate over a range of integer values are very common.

• To simplify the creation of such loops, Python provides the range function for generating a sequence of integers that can be used with the for loop.

• The loop code:

for i in range(1, 10) : # i = 1, 2, 3, ..., 9print(i)

prints the sequential values from 1 to 9. The range function generates a sequence of values based on its arguments.

• The first argument of the range function is the first value in the sequence.

• Values are included in the sequence while they are less than the second argument

Image Credit: www.best-of-web.com

Page 37: An Introduction To Python - Python Midterm Review

You Can Do The Same Thing With While And For Loops

for i in range(1, 10) : # i = 1, 2, 3, ..., 9print(i)

i = 1while i < 10 :

print(i)i = i + 1

Image Credit: www.rgbstock.com

Note that the ending value (the second argument to the range function) is not included

in the sequence, so the equivalent while loop stops before reaching that value, too.

Page 38: An Introduction To Python - Python Midterm Review

Stepping Out…

• By default, the range function creates the sequence in steps of 1. This can be changedby including a step value as the third argument to the function:

for i in range(1, 10, 2) : # i = 1, 3, 5, ..., 9print(i)

Image Credit: megmedina.com

Page 39: An Introduction To Python - Python Midterm Review

Review: The Many Different Forms Of A Range

Page 40: An Introduction To Python - Python Midterm Review

Secret Form Of print Statement

• Python provides a special form of the print function that prevents it from starting a new line after its arguments are displayed.

print(value1, value2, end="")

• By including end="" as the last argument to the first print function, we indicate that an empty string is to be printed after the last argument is printed instead of starting a new line.

• The output of the next print function starts on the same line where the previous one left off.

Image Credit: www.clipartpanda.com

Page 41: An Introduction To Python - Python Midterm 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

Page 42: An Introduction To Python - Python Midterm 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 43: An Introduction To Python - Python Midterm Review

Access Your List Data Using The Square Bracket Notation

print (prerequisites[0]) COP 2271c

print (prerequisites[1]) Introduction to Computation and Programming

print (prerequisites[2]) 3

Image Credit: Clipart Panda

Page 44: An Introduction To Python - Python Midterm Review

You Can Create Multidimensional Lists

• Lists can hold data of mixed type.

• But it gets even better than that: lists can hold collections of anything, including other lists.

• Simply embed the inner list within the enclosing list as needed.

multiDim = [[123],[456],[789]] =1 2 34 5 67 8 9

Image Credit: www.rafainspirationhomedecor.com

Page 45: An Introduction To Python - Python Midterm Review

Playing With Lists: Append

• Add teacher: Dr. Jim Anderson

• Add year: 2015

Note: Python lists can contain data of mixed types. You can mix strings with numbers within the same Python list. You can mix more than just strings and numbers -- you can store data of any type in a single list.

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

Image Credit: ClipArt Best

Page 46: An Introduction To Python - Python Midterm Review

Playing With Lists: Pop

• Allows you to remove the item that is at the end of a list

prereqs[course].pop()

CHM 2045 , Chemistry 1 , 3 , Dr. Anderson , 2015X

Image Credit: blog.poolproducts.com

Page 47: An Introduction To Python - Python Midterm Review

Playing With Lists: Remove

• Allows you to specify which list item you want to remove no matter where in the list it is located

prereqs[course].remove("Dr. Anderson")

CHM 2045 , Chemistry 1 , 3 , Dr. AndersonX

Image Credit: www.pinterest.com

Page 48: An Introduction To Python - Python Midterm Review

Playing With Lists: Insert

• Allows you to add an item to a list in a specified location on the list

prereqs[course].insert(2,"Really Hard")

CHM 2045 , Chemistry 1 , Really Hard , 3

Image Credit: ekskavatör

Page 49: An Introduction To Python - Python Midterm Review

Playing With Lists: Extend

• Allows multiple list items to be added to an existing list

prereqs[course].extend(["Dr. Anderson", "2015"])

CHM 2045 , Chemistry 1 , Really Hard , 3 , Dr. Anderson , 2015

Image Credit: www.clipartpanda.com

Page 50: An Introduction To Python - Python Midterm 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 51: An Introduction To Python - Python Midterm Review

Appending Elements

• Start with an empty listgoodFood=[]

• 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

Page 52: An Introduction To Python - Python Midterm Review

Inserting an Element

• Sometimes, however, the order is important and a new element has to beinserted 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

Page 53: An Introduction To Python - Python Midterm 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

Page 54: An Introduction To Python - Python Midterm 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

Page 55: An Introduction To Python - Python Midterm Review

Let’s Talk About: Tables

• It often happens that you want to storecollections of values that have a two-dimensional tabular layout.

• Such data sets commonly occur in financial and scientific applications.

• An arrangement consisting of rows and columns of values is called a table, or a matrix.

Image Credit: www.rafainspirationhomedecor.com

Page 56: An Introduction To Python - Python Midterm Review

How To Create Tables

• Python does not have a data type for creating tables.

• A two-dimensional tabular structure can be created using Python lists.

• A table is simply a list in which each element is itself another list

Page 57: An Introduction To Python - Python Midterm Review

Accessing Elements Of A Table

• To access a particular element in the table, you need to specify two index values inseparate brackets to select the row and column, respectively.

medalCount = counts[3][1] = 0

Page 58: An Introduction To Python - Python Midterm Review

That’s All!