Changes

Jump to: navigation, search

OPS435 Python Lab 3

3,214 bytes removed, 19:24, 31 January 2019
PART 2 - Manipulating Items in Lists
= LAB OBJECTIVES =
:In previous labs, you learned some programming tools in order to make your Python scripts '''more functional''' and allowed your Python script to run differently based on different data or situations. These tools included '''objects/variables''', '''condition statements''' and '''loops'''. The utilization of these basic tools not only apply to Python scripts, but basically all programming languages including interpreted (including '''Perl scripts''', '''Bash Shell scripts''', '''JavaScript''', etc ) and compiled languages (including '''C''', '''C++''', '''Java''', etc).
:In this lab, you will learn '''functions''', '''lists''', and '''loops''', with the primary focus on creating reusable code.
= INVESTIGATION 1: CREATING THE SIMPLEST FUNCTIONS =
:A very simple definition of using '''functions''' is to create and reuse '''smaller programs within a larger program'''. In programming languages such as '''C''', '''C++''' and '''Java''', commonly used functions are pre-packaged in '''libraries'''. This relates to dependency issues that were discussed when compiling C programming code in your OPS235 course: if a supporting library is missing, the program would not be able to run the called function.
:Usually, a '''function''' will '''contain programming code''' in some part of the python file (most likely near the top of the file, before the main program). We refer to that as a '''"function declaration"'''.
== PART 1 - How User-Defined Functions are Declared and Run ==
:Functions may be designed :* '''not to accept arguments or return a value''', designed * to '''not accept arguments but not return a value''', designed * to '''accept arguments and not return a value''', * or designed to '''both accept arguments and return a value'''. In this investigation, will we will focus of creating functions that either do NOT return a value, or return a value.
'''Functions and Strings'''
: You will now learn how to define and run functions that will return '''string data''' when a function is called.
 
:Let's experiment with defining and running functions. Using iPython you can define and run functions in your sesion and call them from the iPython shell to test them out prior to adding them into scripts. You will learn how to do this.
:'''Perform the Following Steps:'''
import lab3a
text = lab3a.return_text_value()
print(text)
lab3a.return_number_value()
</source> You should notice that all of the function calls should now work.
if __name__ == '__main__':
print('python code')
print(sum_numbers(10, 5))
print(subtract_numbers(10, 5))
:'''Perform the Following Instructions:'''
:#Create the '''~/ops435/lab3/lab3c.py''' script. The purpose of the script is to have a single function that can perform addition, subtraction, or multiplication on a pair of numbers. But the function will allow us to choose exatly what operation we are performing on it when we call it. If the operate function does NOT understand the operator given, it should return an error message(e.g. calling the function to 'divide' two numbers).
:#Use this template to get started:<source lang="python">
#!/usr/bin/env python3
import lab3c
lab3c.operate(10, 20, 'add')
# Will output return 30
lab3c.operate(2, 3, 'add')
# Will output return 5
lab3c.operate(100, 5, 'subtract')
# Will output return 95
lab3c.operate(10, 20, 'subtract')
# Will output return -10
lab3c.operate(5, 5, 'multiply')
# Will output return 25
lab3c.operate(10, 100, 'multiply')
# Will output return 1000
lab3c.operate(100, 5, 'divide')
# Will output return Error: function operator can be "add", "subtract", or "multiply"
lab3c.operate(100, 5, 'power')
# Will output return Error: function operator can be "add", "subtract", or "multiply"
</source>
:::3. Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
:#To demonstrate, issue the following:<source lang="python">
p = subprocess.Popen(['date'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
dir(p)
</source>This function call and the following step is full of details we haven't yet talked about which is why it may look a little scary. By the time we're finished with the course - you will be able to look at code like this and not be intimidated. If you're curious and want to look ahead - you can find the definition for the [https://docs.python.org/3/library/subprocess.html#subprocess.Popen Popen function in the Python reference manual].
:#This next step is going to communicate with the process and get the retrieve it's output (stdout).<source>
import lab3d
lab3d.free_space()
'# Will return 9.6G'
</source></li>
<li>Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
= INVESTIGATION 3: USING LISTS =
:'''Lists''' are one of the most powerful '''data-types''' in Python. A list is a series of '''comma separated values found between square brackets'''. Values in a list can be anything: '''strings''', '''integers''', '''objects''', even '''other lists'''. In this section, you will introduce lists and how to use them effectively, you will further user lists in later labs. It is important to realise that although lists may appear very similar to arraysin other languages, they are different in a number of aspects including which functions are used to manipulate lists as opposed to which functions are used to manipulate arraysthe fact that they don't have a fixed size.
== PART 1 - Navigating Items in Lists ==
:'''Perform the Following Steps'''
:#Start the ipython3 shellCreate a new Python file for testing things in this section.:<source>ipython3</source>You will now create #Create a few lists with different values: list1 contains only '''integers''', list2 contains only '''strings''', list3 contains a combination of both '''integers and strings'''.<br><br>:#Issue the following from the ipython shell:<source lang="python">
list1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
list2 = [ 'uli101', 'ops235', 'ops335', 'ops435', 'ops535', 'ops635' ]
list3 = [ 'uli101', 1, 'ops235', 2, 'ops335', 3, 'ops435', 4, 'ops535', 5, 'ops635', 6 ]
</source>List are constructed similar to arrays. The best way to get access individual '''elements''' from in a list is using the list '''index'''.<br>The index is a number starting from 0 to ('''number_of_items - 1'''), the list index starts counting at '''0'''.<br><br>:#Issue the following Inspect specified elements in the ipython shell to obtain stored datayour lists:<source lang="python">print(list1[0] ) # First element in list1print(list2[1] ) # Second element in list2print(list3[-1] ) # Last element in list3</source>:#Issue the following to retrieve ranges (slices) of items from a list: <source lang="python">list1[0:5] # Starting with index 0 and stopping before index 5list2[2:4] # Starting with index 2 and stopping before index 4list3[3:] # Starting with index 3 and going to the end</source>Lists can also contain other lists. This means data can be contained in: lists of strings, lists of integers, or lists contains a combination of strings and integers.<br><br>:#Issue of the following to create a list that contains lists:<source lang="python">list4 = [ [1, 2, 3, 4], ['a', 'b', 'c', 'd'], [ 5, 6, 'e', 'f' ] ]</source>The list just created only has 3 index locations. Each index points the individual list stored as the list element. <source>list4[0]list4[1]list4[2]</source>:#To access a list inside another list, a second index is needed. Spend some time trying out the syntax and try and navigate to a specific spot in the list.<source lang="python">list4[0][0] # First element in first listlist4[0][-1] # Last element in first listlist4[2][0:2] # First two elements in third list
</source>
:#You can use different elements also retrieve ranges of items from existing lists to create new lists. To demonstrate, issue the followinga list (these are called slices):<source lang="python">first_only_list = [ print(list1[0:5], ) # Starting with index 0 and stopping before index 5print(list2[02:4], ) # Starting with index 2 and stopping before index 4print(list3[03:] ]first_only_list) # Starting with index 3 and going to the end
</source>
#!/usr/bin/env python3
# Create the list called "my_list" below this command (here, not within any function defined below).# That makes it a global variable. We'll talk about that in another lab.
def give_list():
# Does not accept any arguments
# Returns all of the entire list global variable my_list unchanged
def give_first_item():
# Does not accept any arguments
# Returns a single string that is the first item in the listglobal my_list
def give_first_and_last_item():
# Does not accept any arguments
# Returns a list that includes the first and last items in the listglobal my_list
def give_second_and_third_item():
# Does not accept any arguments
# Returns a list that includes the second and third items in the listglobal my_list
if __name__ == '__main__': # This section also referred to as a "boiler platemain code"
print(give_list())
print(give_first_item())
:::'''Sample Run 1:'''<source>
run ./ lab3e.py
[100, 200, 300, 'six hundred']
100
[200, 300]
</source>
:::'''Sample Run 2 (with importfrom another script):'''<source>
import lab3e
lab3e.give_list()
# Will print [100, 200, 300, 'six hundred']
lab3e.give_first_item()
# Will print 100
lab3e.give_first_and_last_item()
# Will print [100, 'six hundred']
lab3e.give_second_and_third_item()
# Will print [200, 300]
</source>
:::3. Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<source>
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
python3 ./CheckLab3.py -f -v lab3e
</source>
:::4. Before proceeding, make certain that you identify any and all errors in lab3e.py. When the checking script tells you everything is OK before proceeding - proceed to the next step.
== PART 2 - Manipulating Items in Lists ==
:'''Perform the Following Steps:'''
:#Start the ipython3 shell:<source>ipython3</source>:#Let's perform a simple change to a list element. Issue Try the following in the ipython shellcode:<source lang="python">
courses = [ 'uli101', 'ops235', 'ops335', 'ops435', 'ops535', 'ops635' ]
print(courses[0])
courses[0] = 'eac150'
print(courses[0])print(courses)</source>It might be useful to change a list element-by-element, but there are other more efficient methods of changing a list (for example: using functions). You will now use the '''dir()''' and '''help()''' functions to see what functions and attributes are available for manipulating lists. The '''help()''' function will also give us tips on how to use those functions. For example, you can use issue help(list-name) in order to see what functions are available to use for that list specific list.<br><br>:#Issue the following:<source lang="python">dir(courses)help(courses)</source>Below are some examples of using built-in functions to '''manipulate''' lists. Take your time to see how each function can be a useful tool for making changes to existing lists.<br><br>:#Issue the following:<source lang="python">help(courses.append)
courses.append('ops235') # Add a new item to the end of the list
print(courses)
help(courses.insert)
courses.insert(0, 'hwd101') # Add a new item to the specified index location
print(courses)
help(courses.remove)
courses.remove('ops335') # Remove first occurrence of value
print(courses)
help(courses.sort)
sorted_courses = courses.copy() # Create a copy of the courses list
sorted_courses.sort() # Sort the new list
print(courses)print(sorted_courses)
</source>:#In addition to using functions to manipulate lists, there are functions that are useful to provide '''information''' regarding the list such as number of elements in a list, the smallest value and largest value in a list.<br><br> :#Issue the following:<source lang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
length_of_list = len(list_of_numbers) # Returns the length of the listsmallest_in_list = min(list_of_numbers) # Returns the smallest value in the listlargest_in_list = max(list_of_numbers) # Returns the largest value in the list</source>In addition to manipulating and obtaining characteristics of a list, it # Notice how the long line below is also useful wrapped to be able to '''perform searches''' for values within lists and obtain the location of values for elements contained within a list. The '''indexfit on one screen:print()''' function allows searching inside a list for a value, it will return the index number of the first occurence. <source lang="pythonList length is ">number = 10help+ str(list_of_numbers.indexlength_of_list)+ list_of_numbers.index(number) # Return index of the number searched for</source>One common annoyance that can occur when performing searches are '''error messages''' when performing a search for an ", smallest element that happens NOT to exist in the list. A good way to prevent those type of errors is to use an '''if''' statement to check to see if the value for an element is in a list, then the appropriate search can be performed for that existing element value.<br><br>:#Issue the following:<source lang="python">list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]number = 7if number in list_of_numbers: # Returns True if value in list, returns False if item not in list number_index = list_of_numbers.index(number) print('index is: ' + str(number_index)smallest_in_list)+else: # If ", largest element in the statement list is False, the else will run print(" + str(numberlargest_in_list) + ' is not in list_of_numbers')
</source>
== PART 3 - Iterating Over Lists ==
:This last section demonstrates an extremely useful for lists: the ability to quickly '''loop through every value in the list'''. '''For loops''' have a set number of times they loop. The '''for''' loop will execute all indented code for each item (element) in the list. Using loops with list allow for efficient processing of stored data.
:'''Perform the Following Steps'''
::Let's take a moment to understand how the '''for''' loop works. This The following '''for''' loop will store the value of each list element from list_of_numbers within a variable named '''item''' and run code indented below the loop for each item.<br><br>:#Issue the following in the ipython shellRun this from a temporary Python file:<source lang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
for item in list_of_numbers:
new_list_of_numbers = square_list(list_of_numbers)
print(list_of_numbers)print(new_list_of_numbers)</source>The above is just one example of a quick use of for loops mixed with lists. But be careful when passing lists into functions. When you give a function a list as an argument, it is the actual list reference and NOT a copy. This means a function can completely change the list without making a new list. While you do have to be careful this is can also be useful, a function can modify any given list, without have to return or store it.<br><br>
:#To demonstrate, run the following code:<source lang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
numbers.remove(5)
delete_numbers(list_of_numbers)
print(list_of_numbers)
</source>
def add_item_to_list(ordered_list):
# Appends new item to end of list which is with the value (last item + 1)
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
# Main code
if __name__ == '__main__':
print(my_list)
:::*The missing list should have the values: '''1, 2, 3, 4, 5'''
:::*The script program should have a function called '''add_item_to_list(ordered_list)'''<dd><dl>This function takes a single argument which is a list name itself. It will then look at the value of the last existing item in the list, it will then append a new value that is one unit bigger (i.e. '''+1''' and modifying that same list without returning any value).</dl></dd>:::*The script should have a function called '''remove_items_from_list(ordered_list, items_to_remove)'''<dd><dl>This function takes two arguments: a list, and a list of numbers to remove from the list. This function will then check if those items exist within that list, and if they exist, then they will be removed. This function will modify the list without returning any value.</dl></dd>
:::'''Sample Run 1:'''<source>
:::'''Sample Run 2 (with import):'''<source>
from lab3f import * [1/1899]print(my_list)# Will print [1, 2, 3, 4, 5]
add_item_to_list(my_list)
add_item_to_list(my_list)
add_item_to_list(my_list)
print(my_list)# Will print [1, 2, 3, 4, 5, 6, 7, 8]
remove_items_from_list(my_list, [1,5,6])
print(my_list)# Will print [2, 3, 4, 7, 8]
</source>
:::2. Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<source>
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
python3 ./CheckLab3.py -f -v lab3f
</source>
:::3. Before proceeding, make certain that you identify any and all errors in lab3f.py. When the checking script tells you everything is OK before proceeding - proceed to the next step.
= LAB 3 SIGN OFF (SHOW INSTRUCTOR) =
:# What is the purpose of the '''system()''' function?
:# What is the purpose of a '''list'''?
:# Assume that the following command was issued at the ipython3 promptlist has been defined: '''mylist = [ 'apple', 1, 'grape', 2, 'banana', 3, ]'''<br>Based on the command issued abovethat, what are the results of will the following commandscontain?<blockquotesource lang="python">'''mylist[0]''' , '''mylist[3]''' , '''mylist[-1]''' , '''mylist[0:1]'''</blockquotesource>:# Assume that the following command was issued at the ipython3 promptlist has been defined: '''combined_list = [ [7, 5], ['x', 'y'], [ 5, 'f' ] ]'''<br>Based on the command issued abovethat, what are the results of will the following commandscontain?<blockquotesource lang="python">'''combined_list[0]''' , '''combined_list[1]''' , '''combined_list[1][0]''' , '''combined_list[2][0:2]'''</blockquotesource>
:# Briefly explain the purpose of each of the following functions (methods) that can be used with lists: '''append''', '''insert''', '''remove''', '''sort''', '''copy'''.</li>
:# Write the '''functions''' that perform the following operations on a list:<ol type="a"><li>Returns the length of the list</li><li>Returns the smallest value in the list</li><li>Returns the largest value in the list</li></ol>
1,760
edits

Navigation menu