Text
stringlengths
1
9.41k
The name of the func-** tion is a variable that refers to a function object. **header The first line of a function definition.** **import statement A statement that reads a module file and creates a module** object. **module object A value created by an import statement that provides access to** the data and code de...
If a function call is used as an expression,** the return value is the value of the expression. **void function A function that does not return a value.** ##### 4.14 Exercises Exercise 4: What is the purpose of the “def” keyword in Python? a) It is slang that means “the following code is really cool” b) It indicate...
Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.
Because iteration is so common, Python provides several language features to make it easier. One form of iteration in Python is the while statement.
Here is a simple program that counts down from five and then says “Blastoff!”. ----- n = 5 **while n > 0:** print(n) n = n - 1 print('Blastoff!') You can almost read the while statement as if it were English.
It means, “While n is greater than 0, display the value of n and then reduce the value of n by 1. When you get to 0, exit the while statement and display the word Blastoff!” More formally, here is the flow of execution for a while statement: 1.
Evaluate the condition, yielding True or False. 2. If the condition is false, exit the while statement and continue execution at the next statement. 3.
If the condition is true, execute the body and then go back to step 1. This type of flow is called a loop because the third step loops back around to the top.
We call each time we execute the body of the loop an iteration.
For the above loop, we would say, “It had five iterations”, which means that the body of the loop was executed five times. The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates.
We call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable.
If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop. ##### 5.3 Infinite loops An endless source of amusement for programmers is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop because there is no iteration variable telling you ho...
Other times a loop is obviously infinite because it has no iteration variable at all. ##### 5.4 “Infinite loops” and break Sometimes you don’t know it’s time to end a loop until you get half way through the body.
In that case you can write an infinite loop on purpose and then use the break statement to jump out of the loop. This loop is obviously an infinite loop because the logical expression on the while statement is simply the logical constant True: ----- n = 10 **while True:** print(n, end=' ') n = n - 1 print('Done!'...
This program will run forever or until your battery runs out because the logical expression at the top of the loop is always true by virtue of the fact that the expression is the constant value True. While this is a dysfunctional infinite loop, we can still use this pattern to build useful loops as long as we carefull...
If the user types done, the break statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop.
Here’s a sample run: - hello there hello there - finished finished - done Done! This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going...
In that case you can use the continue ----- statement to skip to the next iteration without finishing the body of the loop for the current iteration. Here is an example of a loop that copies its input until the user types “done”, but treats lines that start with the hash character as lines not to be printed (kind o...
When we have a list of things to loop through, we can construct a definite loop using a for statement.
We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set. The syntax of a for loop is similar to the while loop in that there is a for state...
The variable friend changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable. ##### 5.7 Loop patterns Often we use a for or while loop to go through a list of items or the contents of a file and ...
Our iteration variable is named itervar and while we do not use itervar in the loop, it does control the loop and cause the loop body to be executed once for each of the values in the list. In the body of the loop, we add 1 to the current value of count for each of the values in the list.
While the loop is executing, the value of count is the number of values we have seen “so far”. Once the loop completes, the value of count is the total number of items.
The total number “falls in our lap” at the end of the loop.
We construct the loop so that we have what we want when the loop finishes. Another similar loop that computes the total of a set of numbers is as follows: total = 0 **for itervar in [3, 41, 12, 9, 74, 15]:** total = total + itervar print('Total: ', total) In this loop we do use the iteration variable.
Instead of simply adding one to the count as in the previous loop, we add the actual number (3, 41, 12, etc.) to the running total during each loop iteration.
If you think about the variable total, it contains the “running total of the values so far”.
So before the loop starts total is zero because we have not yet seen any values, during the loop total is the running total, and at the end of the loop total is the overall total of all the values in the list. As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes called...
None is a special constant value which we can store in a variable to mark the variable as “empty”. Before the loop starts, the largest value we have seen so far is None since we have not yet seen any values.
While the loop is executing, if largest is None then we take the first value we see as the largest so far.
You can see in the first iteration when the value of itervar is 3, since largest is None, we immediately set largest to be 3. After the first iteration, largest is no longer None, so the second part of the compound logical expression that checks itervar > largest triggers only when we see a value that is larger than t...
When we see a new “even larger” value we take that new value for largest.
You can see in the program output that largest progresses from 3 to 41 to 74. At the end of the loop, we have scanned all of the values and the variable largest now does contain the largest value in the list. To compute the smallest number, the code is very similar with one small change: smallest = None print('Befor...
More code means more chances to make an error and more places for bugs to hide. One way to cut your debugging time is “debugging by bisection.” For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps. Instead, try to break the problem in half.
Look at the middle of the program, or near it, for an intermediate value you can check.
Add a print statement (or something else that has a verifiable effect) and run the program. If the mid-point check is incorrect, the problem must be in the first half of the program.
If it is correct, the problem is in the second half. Every time you perform a check like this, you halve the number of lines you have to search.
After six steps (which is much less than 100), you would be down to one or two lines of code, at least in theory. In practice it is not always clear what the “middle of the program” is and not always possible to check it.
It doesn’t make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check.
Then choose a spot where you think the chances are about the same that the bug is before or after the check. ##### 5.9 Glossary **accumulator A variable used in a loop to add up or accumulate a result.** **counter A variable used in a loop to count the number of times something hap-** pened.
We initialize a counter to zero and then increment the counter each time we want to “count” something. **decrement An update that decreases the value of a variable.** **initialize An assignment that gives an initial value to a variable that will be** updated. **increment An update that increases the value of a varia...
Once “done” is entered, print out the total, count, and average of the numbers.
If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. Enter a number: 4 Enter a number: 5 Enter a number: bad data Invalid input Enter a number: 7 Enter a number: done 16 3 5.333333333333333 Exercise 2: Write another program ...
You can access the characters one at a time with the bracket operator: >>> fruit = 'banana' >>> letter = fruit[1] The second statement extracts the character at index position 1 from the fruit variable and assigns it to the letter variable. The expression in brackets is called an index.
The index indicates which character in the sequence you want (hence the name). But you might not get what you expect: >>> print(letter) a For most people, the first letter of “banana” is b, not a.
But in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero. >>> letter = fruit[0] >>> print(letter) b So b is the 0th letter (“zero-eth”) of “banana”, a is the 1th letter (“one-eth”), and n is the 2th (“two-eth”) letter. You can use any expression, including va...
Otherwise you get: >>> letter = fruit[1.5] TypeError: string indices must be integers ----- ## b ##### [0] ## a ##### [1] ## n ##### [2] ## a ##### [3] ## n ##### [4] ## a ##### [5] Figure 6.1: String Indexes ##### 6.2 Getting the length of a string using len len is a built-in function that ret...
Since we started counting at zero, the six letters are numbered 0 to 5.
To get the last character, you have to subtract 1 from length: >>> last = fruit[length-1] >>> print(last) a Alternatively, you can use negative indices, which count backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on. ##### 6.3 Traversal through a string with a loop A lot of computations involve processing a string one character at a time.
Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal.
One way to write a traversal is with a while loop: index = 0 **while index < len(fruit):** letter = fruit[index] print(letter) index = index + 1 ----- This loop traverses the string and displays each letter on a line by itself.
The loop condition is index \< len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed.
The last character accessed is the one with the index len(fruit)-1, which is the last character in the string. Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. Ano...
The loop continues until no characters are left. ##### 6.4 String slices A segment of a string is called a slice.
Selecting a slice is similar to selecting a character: >>> s = 'Monty Python' >>> print(s[0:5]) Monty >>> print(s[6:12]) Python The operator returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. If you omit the first index (before the colon), ...
If you omit the second index, the slice goes to the end of the string: >>> fruit = 'banana' >>> fruit[:3] _'ban'_ >>> fruit[3:] _'ana'_ If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks: >>> fruit = 'banana' >>> fruit[3:3] _''_ An empty strin...
For example: >>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment The “object” in this case is the string and the “item” is the character you tried to assign.
For now, an object is the same thing as a value, but we will refine that definition later.
An item is one of the values in a sequence. The reason for the error is that strings are immutable, which means you can’t change an existing string.
The best you can do is create a new string that is a variation on the original: >>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print(new_greeting) Jello, world! This example concatenates a new first letter onto a slice of greeting.
It has no effect on the original string. ##### 6.6 Looping and counting The following program counts the number of times the letter a appears in a string: word = 'banana' count = 0 **for letter in word:** **if letter == 'a':** count = count + 1 print(count) This program demonstrates another pattern of computation...
The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result: the total number of a’s. Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. ----- ##### 6.7 The...
To see if two strings are equal: **if word == 'banana':** print('All right, bananas.') Other comparison operations are useful for putting words in alphabetical order: **if word < 'banana':** print('Your word,' + word + ', comes before banana.') **elif word > 'banana':** print('Your word,' + word + ', comes after...
All the uppercase letters come before all the lowercase letters, so: Your word, Pineapple, comes before banana. A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison.
Keep that in mind in case you have to defend yourself against a man armed with a Pineapple. ##### 6.9 string methods Strings are an example of Python objects.
An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object. Python has a function called dir which lists the methods available for an object. The type function shows the type of an object and the di...
make the first character have upper case and the rest lower case. >>> While the dir function lists the methods, and you can use help to get some simple documentation on a method, a better source of documentation for string methods [would be https://docs.python.org/3.5/library/stdtypes.html#string-methods.](https://doc...
We call a method by appending the method name to the variable name using the period as a delimiter. For example, the method upper takes a string and returns a new string with all uppercase letters: Instead of the function syntax upper(word), it uses the method syntax word.upper(). >>> word = 'banana' >>> new_word = ...
The empty parentheses indicate that this method takes no argument. A method call is called an invocation; in this case, we would say that we are invoking upper on the word. For example, there is a string method named find that searches for the position of one string within another: ----- >>> word = 'banana' >>> in...
As long as we are careful with the order, we can make multiple method calls in a single expression. Exercise 4: There is a string method called count that is similar to the function in the previous exercise.
Read the documentation of this method at [https://docs.python.org/3.5/library/stdtypes.html#string-methods and write an](https://docs.python.org/3.5/library/stdtypes.html#string-methods) invocation that counts the number of times the letter a occurs in “banana”. ----- ##### 6.10 Parsing strings Often, we want to l...
For example if we were presented a series of lines formatted as follows: From stephen.marquard@ uct.ac.za Sat Jan 5 09:14:16 2008 and we wanted to pull out only the second half of the address (i.e., uct.ac.za) from each line, we can do this by using the find method and string slicing. First, we will find the positio...
Then we will find the position of the first space after the at-sign.
And then we will use string slicing to extract the portion of the string which we are looking for. >>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' >>> atpos = data.find('@') >>> print(atpos) 21 >>> sppos = data.find(' ',atpos) >>> print(sppos) 31 >>> host = data[atpos+1:sppos] >>> print(host) uct...
When we slice, we extract the characters from “one beyond the at-sign through up to but not including the space character”. The documentation for the find method is available at [https://docs.python.org/3.5/library/stdtypes.html#string-methods.](https://docs.python.org/3.5/library/stdtypes.html#string-methods) #####...
When applied to integers, % is the modulus operator.
But when the first operand is a string, % is the format operator. The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted.
The result is a string. For example, the format sequence “%d” means that the second operand should be formatted as an integer (d stands for “decimal”): >>> camels = 42 >>> '%d' % camels _'42'_ ----- The result is the string “42”, which is not to be confused with the integer value 42. A format sequence can appear ...
Each format sequence is matched with an element of the tuple, in order. The following example uses “%d” to format an integer, “%g” to format a floatingpoint number (don’t ask why), and “%s” to format a string: >>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') _'In 3 years I have spotted 0.1 camels.'_ The ...
The types of the elements also must match the format sequences: >>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: %d format: a number is required, not str In the first example, there aren’t enough elements; in the second, the element is the wrong type. The form...
You can read more about it at [https://docs.python.org/3.5/library/stdtypes.html#printf-style-string-formatting.](https://docs.python.org/3.5/library/stdtypes.html#printf-style-string-formatting) ##### 6.12 Debugging A skill that you should cultivate as you program is always asking yourself, “What could go wrong her...
We will cover tuples in Chapter 10 ----- **if line[0] == '#':** **continue** **if line == 'done':** **break** print(line) print('Done!') _# Code: http://www.pythonlearn.com/code3/copytildone2.py_ Look what happens when the user enters an empty line of input: - hello there hello there - # don't print this - ...
Then there is no zero-th character, so we get a traceback.
There are two solutions to this to make line three “safe” even if the line is empty. One possibility is to simply use the startswith method which returns False if the string is empty. if line.startswith('#'): Another way is to safely write the if statement using the guardian pattern and make sure the second logical ...
For now, you can use “object” and** “value” interchangeably. **search A pattern of traversal that stops when it finds what it is looking for.** **sequence An ordered set; that is, a set of values where each value is identified by** an integer index. **slice A part of a string specified by a range of indices.** **tr...
strip and replace are particularly useful. The documentation uses a syntax that might be confusing. For example, in find(sub[, start[, end]]), the brackets indicate optional arguments.
So sub is required, but start is optional, and if you include start, then end is optional. ----- ## Chapter 7 # Files ##### 7.1 Persistence So far, we have learned how to write programs and communicate our intentions to the Central Processing Unit using conditional execution, functions, and iterations. We have le...
The CPU and memory are where our software works and runs.
It is where all of the “thinking” happens. But if you recall from our hardware architecture discussions, once the power is turned off, anything stored in either the CPU or main memory is erased.
So up to now, our programs have just been transient fun exercises to learn Python. ###### Secondary Memory Figure 7.1: Secondary Memory In this chapter, we start to work with Secondary Memory (or files).
Secondary memory is not erased when the power is turned off.
Or in the case of a USB flash drive, the data we write from our programs can be removed from the system and transported to another system. ----- We will primarily focus on reading and writing text files such as those we create in a text editor.
Later we will see how to work with database files which are binary files, specifically designed to be read and written through database software. ##### 7.2 Opening files When we want to read or write a file (say on your hard drive), we first must _open the file.
Opening the file communicates with your operating system, which_ knows where the data for each file is stored.
When you open a file, you are asking the operating system to find the file by name and make sure the file exists.
In this example, we open the file mbox.txt, which should be stored in the same folder that you are in when you start Python.
You can download this file from [www.pythonlearn.com/code3/mbox.txt](http://www.pythonlearn.com/code3/mbox.txt) >>> fhand = open('mbox.txt') >>> print(fhand) <_io.TextIOWrapper name='mbox.txt' mode='r' encoding='cp1252'> If the open is successful, the operating system returns us a file handle.
The file handle is not the actual data contained in the file, but instead it is a “handle” that we can use to read the data.
You are given a handle if the requested file exists and you have the proper permissions to read the file. |open|H A N D L E|Col3| |---|---|---| |close||| |read||| |write||| |open H A close N D read L write E Your Program|From stephen.m..