With Many Thanks to Dr. Amber Settle for the Original Version of These Notes
Total Page:16
File Type:pdf, Size:1020Kb
CSC 241 NOTES Yosef Mendelsohn
With many thanks to Dr. Amber Settle for the original version of these notes. Prof Settle's notes in turn are based on the Perkovic text.
Loop pattern: Infinite loop It is also possible to create a so called “infinite” loop, i.e. a loop that runs forever. Usually, infinite loops are the result of sloppy programming.
However, there are occasionally situations where they are useful. For example, a service that is needed to be executed indefinitely. A web server, i.e. a program that serves web pages, is an example of a program that provides a service that has no known end point.
Perhaps the easiest way to create an infinite loop intentionally is:
while True:
This loop can only be broken by typing (simultaneously) Ctrl-C on the keyboard of the console computer where the program is running.
Practice problem: Write a function hello() that, repeatedly without end, requests that the user input their name and then greets the user using that name.
Recall that an infinite loop happens when the condition after the ‘while’ term always evaluates to True. I.e. It never becomes false.
The following is an example of how the function would be used:
>>> hello() What’s your name? Amber Hello Amber What’s your name? Marcus Hello Marcus What’s your name?
Loop pattern: Interactive loop A while loop is useful when a program needs to repeatedly request input from the user, until the user enters a flag which is a value indicating the end of the input.
Example: Write a function called ‘betterGreeting()’ which fixes the function above, so that if the user types ‘stop’ (in lower case), the loop ends.
1 Example: Write a function interact1() that repeatedly requests positive integers from the user and appends them to a list. The user will indicate the end of the input with the value 0 or a negative number, at which point the function should return the list of all positive integers entered by the user.
The following is an example of how the function would be used: >>> interact1() Enter value: 3 Enter value: 1 Enter value: 8 Enter value: 0 [3, 1, 8] >>> interact1() Enter value: 0 []
The solution uses the accumulator loop pattern in addition to the interactive loop pattern.
Specialized loop statements There are certain statements that can be used to construct more elegant loops (and other statements).
These are: break, continue, and pass.
The break statement and the loop-and-a-half pattern A break statement immediately terminates the loop. A break statement can be placed anywhere inside the body of the loop. As with any situation in which a loop is ended, execution resumes at the first statement after the body of the loop.
To see how it works, consider writing a variation of the interact1() function, called interact2() in which we use a break statement to exit the loop when the user gives us our 'flag' value.
>>> interact2() Enter value: 3 Enter value: 1 Enter value: 8 Enter value: 0 [3, 1, 8] >>> interact2() Enter value: 0 []
Instead of returning, we can use the break statement inside the function.
The continue statement The continue statement is used to terminate the current iteration of the loop. That is, whereas the break statement completely exits the loop – and does not even try to check the conditional, the continue statement merely terminates the current execution of
2 the body. However, the loop is not over. Flow now returns to the conditional to evaluate for True vs False.
Unlike the break statement, execution is NOT resumed with the first statement after the loop body. Instead, execution resumes at the loop's conditional.
. If the loop is a while loop, execution is resumed at the condition checking statement. If the condition is still true, then execution moves to the next iteration of the while loop. . If the loop is a for loop, then execution resumes with the next iteration only if there are more elements to iterate over.
For example, consider the startsWithVowel() function:
def startsWithVowel(): while True: word = input("Enter a word: ") if word[0] not in 'aeiouAEIOU': continue else: print("Starts with a vowel.")
The print statement is only executed when the condition in the if statement evaluates to False.
This is because the continue statement in the body of the if statement makes the execution skip to the next iteration of the while loop.
Also note that this code has an infinite loop inside. You'll have to press control-C to end the loop. In the real world, this should not happen (or at least only in special circumstances).
The pass statement In Python every body of a function, if statement, for or while loop must contain at least one statement.
Sometimes we just don’t need to do anything inside the body. When that’s the case, we can use the pass statement.
For example: if n % 2 == 0: pass else: print(n)
In the case where n is even, we don’t do anything. When n is odd, we print the number.
The pass statement is especially useful when a body for a particular construct has not yet been written. Basically, this means that you should pretty much only use it during writing/testing of code. For example, for functions that we haven’t
3 implemented. In such a case, it is there as a temporary placeholder until we are ready to implement that section.
However, any “production” code should not have ‘pass’ in it. (For that matter, break and continue should rarely be there either!)
Warning: Be careful how you use break, continue, and pass The specialized statements break, continue, and pass are sometimes used by sloppy programmers because they haven't thought about the problem in an efficient way.
For example, consider this example from earlier:
if n % 2 == 0: pass else: print(n)
How can we rewrite the if statement so that it doesn’t use a pass? Was it necessary to use a break statement in the interact2() function?
Sometimes break, continue, and pass can make your code more elegant and better. But careless programmers frequently use them inappropriately.
As you become a more experienced programmer, you’ll learn the difference.
Rule of thumb: You shouldn't need to use them very often. The pass statement is fine as a temporary measure when you are developing your code. However, it too shouldn't be seen very often in "finished" the product. (i.e. I shouldn't encounter them on assignments very often – or perhaps ever!)
Dictionaries Suppose you want to store employee records with information such as their social security number and name. You'd like to store these in a collection and access the employee records (e.g. name, birthdate, salary, etc, etc) using the employees’ social security numbers.
The list collection is not really useful for this problem because list items must be accessed using an index, i.e. by their position in the collection.
But what if we want a way to access an item in a collection by, say, some kind of key? Dictionaries are a type of collection will allow us to do that.
For this problem we need a collection type that allows access to stored items, but instead of using a position as our index, we use a "key". With dictionaries, we can decide what the key will be. The one requirement is that the key we choose must be unique for every record. For an employee, social security number would be a good choice since no two people can have the same value.
Recall that to create a list we specify an identifier and square brackets:
4 myList = []
Dictionaries are created very similarly, but use braces: myDict = {}
We add items by typing
>>> employees = {'022-83-8795': 'Allison Andover', '987-65-4321': 'Benjamin Benton', '123-45-6789': 'Cassidy Cantor', '874-74-1532': 'Daniel Danton'} Recall that with a list, we would refer to an item using its position. For example, to output the first item in a list we might say:
>>> myList[0]
When working with a dictionary, we refer to an item using its key:
>>> employees['123-45-6789'] 'Cassidy Cantor'
Here is a short summary of some important facts about dictionaries:
A dictionary, also called a map, is a collection type that stores key-value pairs.
In the employees dictionary above, ‘022-83-8795’: ‘Allison Andover’ is known as a "key-value pair".
The key ‘022-83-8795’ is the “index” of the stored object. We use this index to access the object.
The key must be an object of an immutable type (like a string or number or tuple).
The value for the key 022-83-8795 is the string 'Allison Andover'.
Items in a Dictionary are not ordered. Dictionaries are mutable, like lists, meaning they can be modified to contain different items. List lists, dictionaries have dynamic size, meaning they can grow or shrink (i.e. you can add and remove items).
Dictionary methods Because the dict (dictionary) data type is different from the list data type it has different methods.
You can, of course, see these by looking them up in the Python API. For a very quick look, you can type help(dict) at the console.
5 Study and experiment with the following examples:
>>> d = {'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su': 'Sunday'} >>> print(d) {'Fr': 'Friday', 'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday', 'Su': 'Sunday', 'Th': 'Thursday', 'Sa': 'Saturday'} >>> d['We'] 'Wednesday' >>> 'Su' in d True >>> d.keys() dict_keys(['Fr', 'Mo', 'Tu', 'We', 'Su', 'Th', 'Sa']) >>> d.values() dict_values(['Friday', 'Monday', 'Tuesday', 'Wednesday', 'Sunday', 'Thursday', 'Saturday'])
>>> d.items() dict_items([('Fr', 'Friday'), ('Mo', 'Monday'), ('Tu', 'Tuesday'), ('We', 'Wednesday'), ('Su', 'Sunday'), ('Th', 'Thursday'), ('Sa', 'Saturday')]) >>> type(d.keys())
Here is an example where we use the keys() function. Let's output all of the keys in a dictionary, one on each line: for key in dictName.keys(): print(key)
Here is the API for this data type.
Do the following CodeLab exercises found in the Week 7 folder: 51816 51817 51818 51819 51820
6