Changes

Jump to: navigation, search

OPS435 Python Lab 3

212 bytes removed, 21:50, 20 May 2019
m
PART 3 - Iterating Over 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 on 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))
</source>The final '''return "ok"''' will only take place if a previous return has not taken place before it. Once return has been used in a function, the function immediately exits and returns the value.
:#Call describe_temperature like this to confirm the results:<source>
print(describe_temperature(50))
# Will return 'hot'
print(describe_temperature(20))
# Will return 'perfect'
print(describe_temperature(-50))
# Will return 'cold'
print(describe_temperature(25))
# Will return 'ok'
print(describe_temperature(10))
# Will return 'ok'
</source>
:'''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">
:#Create a new python file for testing.
:#Import the '''''os''''' module in your python file.
:#You can issue operating system commands by using the '''system()''' function. Try it:<source lang="python">
os.system('ls')
:#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">
:#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:<source lang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
lengthOfList length_of_list = len(list_of_numbers) # Returns the length of the listsmallestInList smallest_in_list = min(list_of_numbers) # Returns the smallest value in the listlargestInList largest_in_list = max(list_of_numbers) # Returns the largest value in the list
# Notice how the long line below is wrapped to fit on one screen:
print("List length is " + lengthOfList str(length_of_list) + ", smallest element in the list is " + smallestInList str(smallest_in_list) + ", largest element in the list is " + largestInListstr(largest_in_list))
</source>
::The following '''for''' loop will store the value of each 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 . 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>

Navigation menu