Python,。
Requirement
In this practice set, you will be writing quite a few short Python functions; but first, let’s discuss some sample python programs that are similar in nature those I will be asking you to write. Be sure to read through the handout before jumping to the programming practice problems! Do not copy and paste my sample code! Type it!
Sample Program 1
Suppose that you want to iterate through a list and print each element in that list. We could write this program out using a “for loop”. I will name this function iterateThroughList(myList), and refer to this function as Sample Program 1:
1 2 3 4 5 6 7
|
def iterateThroughList (myList): for element in myList: print(element)
|
Let’s take a look at this function. The structure of this “for loop” uses two keywords: for and in. Keywords were briefly discussed in DA Assignment 1. This function iterates through myList, referring to each item in the list as element as it is being manipulated. We are printing each item, and then moving on to the next item in the list, until each item has been printed.
Now type the following program into the python script window:
1 2 3 4 5 6 7 8
|
def printStuff(n): myList = range(0, n) printf(myList) for element in myList: print(element * "hello")
|
Let’s take a look at what this function does. Run this program. Then type the following and think about the results:
gt;gt;gt; printStuff(5) gt;gt;gt; printStuff(10)
Describe what this function does. What does the line “myList = range(0, n)” do?
Sample Program 2
Suppose that you want to create a list consisting of the integer 0 appearing n times. We could write this program out using a “for loop”. I will name this function createListFor(n) and refer to this function Sample Program 2:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
def createListFor(n): myList = []
for value in range(0,n): myList.append(0)
return myList
|
Let’s take a look at this function. This function has to return a list of n zeros, so the first thing that we need to do is create an empty list. Then we need to insert the integer 0 to the list n times. The line “for value in range(0,n)” uses a function called “range”. This is a built-in function that basically iterates through the integers starting with 0 and ending with the value of (n - 1). Remember that in computer science we start counting at 0. So, if we need to do something n times, we can start at 0 and stop at (n - 1). The structure of this “for loop” uses the keyword “for” followed by a variable name (in this case, “value”) then another keyword “in” and then the function “range(0,n)”.
Included in this “for loop” (as indicated by the indentation) is the instruction “myList.append(0)”. This instruction does what you think it does: it will take the list myList and append the integer 0 to the list. Once we are done performing this action n times, we will leave the loop (again, indicated by the indentation) and then return the list that we created.
You should type this code into wing and run it (first press the green arrow to load the program into memory, and then call the function in the python shell to actually see what the function does) to make sure that it runs properly, and that you understand the role of the indentation. Next, experiment with this sample code.
- Change the name of the variable “value” to “element” and run the program and call the function. Then change it back to “value”.
- Indent the “return myList” line to include it in the “for loop” to see what happens. Then move it back to where it belongs.
- Insert two print statements, one immediately before and one immediately after the line “myList.append(0)”: include the line “print(value)” on the line immediately before the line that appends 0 to the list, and include the line “print(myList)” on the line immediately after. Now run the program and call the function.
- Change the line “print(myList)” to the line “print(“The list is: “ + str(myList))” and run the program and call the function.
For each of these changes, pay attention to the output that appears in the shell.
Sample Program 3
Suppose that you want to create a list consisting of the integer 0 appearing n times, but instead of using a “for loop” we will use a “while loop”. I will name this function createListWhile(n), and refer to this function as Sample Program 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
def createListWhile(n): myList = []
while (len(myList) lt; n) myList.append(0)
return myList
|
Let’s compare this function to the first sample program. It starts out the same: we need to create an empty list, and then append things to this list. The difference is in how we iterate. In this function, we are using a different built-in function: len(). Notice that we are writing functions that make use of other functions! We can think of individual functions as modules; many of our more complex functions will be written using this modular framework. But, let’s get back to our length function: len() takes as an argument a list and returns its length. As an aside, play with the length function. What happens if you try to find the length of an integer? Of a Boolean? Of a float? Of a string? This is where you let your curiosity run wild! What is the length of an empty list? Hopefully you tried to find out by typing
gt;gt;gt; len([])
and saw that the response was 0.
Ok, let’s get back to the sample program. The continuation condition in this “while loop” checks to see if the length of our list is the right size. If it is not, we need to keep appending things to the list. Once the length of the list is the correct value, we will exit the iterative loop and return the list that we created.
Type this function into Wing, run the program and call the function in the shell. Do not “copy and paste”. Typing is good exercise! You should get the desired results. Make the following changes to this sample program:
- Modify this function so that the list contains n entries of the string “yibbie”.
- Modify this function so that it uses a counter to keep track of the number of times that “yibbie” has been inserted into the list.
Making changes to a program is a great way to become familiar with the syntax of Python.
Sample Program 4
Suppose you want to create a list that contains a bunch of random numbers. You could need 10 numbers, 100 numbers, or 100,000 numbers. Perhaps you will need to create several such lists, each containing a different number of numbers. Rather than manually typing the first numbers that come to you (which wouldn’t really fit the criteria), you want to automate the process. Let’s take a look at a sample program that tries to accomplish this goal, which I will refer to as Sample Program 4. Feel free to type this program into Wing, paying attention to the indentation. Remember that indentation is one of the keys to Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
import random def randomNumbers(n): myList = []
needMoreNumbers = True
while (needMoreNumbers): randomNumber = int(random.random() * 10)
myList.append(randomNumber)
n=n-1
if (n lt; 1): needMoreNumbers = False
return myList
|
Let me point out a few things in that code that you probably haven’t seen before. One component that you may not have seen before is the use of random, both at the beginning of the program with an import statement, and towards the end, where random.random() appears. The import statement tells the Python interpreter that it should load the library called random. A library is simply a collection of useful algorithms or programs that a programmer may wish to use. In this case, we’ll use a specific function in that library, called random(). This specific function has been given the name random. The function, random(), simply returns - you guessed it - a random number. However, it returns a random decimal number between 0 and 1 (more precisely, it returns a number in the interval [0, 1)…there is a mathematical difference between square braces and parentheses). We want integer numbers in a given range, say 0 - 9, so we’ll just multiply this random number by 10 and “cast it” (or convert it) to an integer, effectively giving us a random number between 0 and 9 (in this case). There are several other ways to generate a random number that is an integer within a given range. See how many ways you can do this (feel free to use Google). I will discuss a few different ways in class.
We typically import all libraries at the beginning of a series of functions in a file. You only need to import a library ONCE in a given file or scripting window. Once a library is imported, it is available to use in every function in the scripting window. For example, if you need the random library and the math library, you’ll have the following as the first two lines of your script, followed by your various functions:
1 2 3 4 5 6 7 8
| import random import math
def myFirstFunction(a, b):
def mySecondFunction(value, words):
|
Another type of variable being used is a Boolean (I realize that in class I tend to focus on 4 data types…I tend to take Booleans for granted). A Boolean type of variable is a variable that can only take on one of two values: True or False. The words True and False have special meaning in python (they would not make good variable names). In some languages, Boolean variables take on the values YES/NO, or 0/1, or true/false (not capitalized). Boolean variables are useful when checking the result of a particular condition: if the condition is met, the value assigned to the variable will be True, and if the condition is not met, the value assigned to the variable will be False. You can set a variable to be either True or False, and then determine its type:
gt;gt;gt; myBool = True gt;gt;gt; type(myBool)
When comparing quantities, the result is a Boolean. For example, type the following into the Python shell and look at the results:
gt;gt;gt;5 gt; 10 gt;gt;gt;4 gt; 10
Another thing to realize is that we are working with a new data type. You have already been introduced to strings (data type str), integers (data type int) and floats (data type float). In this program, we are actually working with two new types of data: Booleans and lists. A list has type “list”. Type the following into the Python shell:
gt;gt;gt;myList = [1, 2, 3, 4, 5] gt;gt;gt;type (myList)
A list is a very interesting (and useful) data type, and python has a bunch of convenient built-in functions that can be used to manipulate lists. We will spend some time with lists in the next couple of weeks, learning about their properties and how to work with them. An empty list can be created using square brackets: [ ]. Lists are ordered (based on their index value), and something can be inserted into a list by using the append() function. You can get the length of a list (or the number of elements in the list) using the function len(name of list). The following code creates an empty list called myList and then adds the string “hello” to this list:
gt;gt;gt;myList = [ ] gt;gt;gt;myList.append(quot;helloquot;)
Try this in the little window in python. At this point, myList contains one element. Verify this by typing:
gt;gt;gt;myList
You should see a list consisting of one element, the word “hello”. If you type
gt;gt;gt;len(myList)
You should get 1. To see if you understand this, add the word “world” to myList. Verify that the length of myList is now 2.
gt;gt;gt;myList gt;gt;gt;len(myList)
Type (don’t copy and paste, but actually type) Sample Program 4 into python, and run it (i.e. call this function) for various values of n. Does it produce the correct number of values? Look at the list to verify that it is doing what you expect it to. Be sure to think about each LINE of the program. Whenever you implement another person’s code, you should take the time to understand it, and play around with it to see how it can be modified to serve a similar purpose. You should understand the logic in the “while” statement. There may be other ways to loop through the process to generate a fixed number of values. Can you modify this code so that the range of values is always between 0 and 250? Can you modify this code so that the function uses a “for” loop rather than a “while” loop? These are rhetorical questions…no need to submit an answer here…at least, not yet. Here is where your fun begins!
Practice Problem 1
Write a function called randNum(n), which does what the previous sample code (Sample Program 4) does, but uses a “for loop” instead of a “while loop” to accomplish the same task. Think of the function randomNumbers(n) as a “helper function” in the sense that it will help you write more complex functions.
Practice Problem 2
Write a function called randNumMaxFor(n, maxValue), which generates a list of n random numbers between 0 and maxValue, inclusive. This function should use a “for loop” to generate the list.
Practice Problem 3
Write a function called randNumMaxWhile(n, maxValue), which generates a list of n random numbers between 0 and maxValue, inclusive. This function should use a “while loop” to generate the list.
Practice Problem 4
Write a function called randNumMinFor(n, minValue), which generates a list of n random numbers between minValue and 1000, inclusive. This function should use a “for loop” to generate the list.
Practice Problem 5
Write a function called randNumMinWhile(n, minValue), which generates a list of n random numbers between minValue and 1000, inclusive. This function should use a “while loop” to generate the list.
Practice Problem 6
Write a function called randNumMinMaxFor(n, minValue, maxValue), which generates a list of n random numbers between minValue and maxValue, inclusive. This function should use a “for loop” to generate the list.
Practice Problem 7
Write a function called randNumMinMaxWhile(n, minValue, maxValue), which generates a list of n random numbers between minValue and maxValue, inclusive. This function should use a “while loop” to generate the list.