1,760
edits
Changes
no edit summary
<font color='red'>
'''** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **'''
</font>
= 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.
:*'''Using and manipulating lists''' to allow for processing a large amount of data quickly
:*'''Looping through lists''' using '''functions'''. Looping (iteration) is the ability for your program to repeatedly run the same code over and over. In this way, you can run a loop that contains a list to better send data to functions for better, more efficient execution of your Python script.
<br><br>
= INVESTIGATION 1: CREATING SIMPLE 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.
:'''Perform the Following Steps:'''
:#To start, open the ipython3 shellCreate a new python file for testing code in this section.:<source>ipython3</source>#Whenever you want to create a function, you must start with the keyword "'''def'''". The '''def''' keyword is used to start the definition of the function, it does not run the code you write. Functions, just like '''if''' statements, must have all code under them indented.<br><br>:# Enter the following code in your ipython3 shell:<sourcelang="python">
def hello():
print('Hello World')
print('Inside a Function')
</source>Remember to press '''ENTER''' a second time to return to the ipython prompt. You may :#Executing your file you should have noticed that nothing happened. Well actually, something did happen... the function called '''hello(''') has been defined and stored in internal memory in order for it to run when called by its function name. Now that our function was created, we can use it over and over. <br><br>:#To execute the code inside the function, run the function name with "'''()'''" '''brackets''' at the end of the function name.<br>Try running the '''hello()''' function by name three times by issuing the following in the ipython3 shelllike this:<sourcelang="python">
hello()
hello()
hello()
</source>You should notice that the function just does the same thing over-and-over no matter how many times your call the function by name. By the way, that is OK. On the other hand, you may want to create and use a function to do something, like perform error checking or some other task that returns a value to the '''main''' program for further processing. For example, a '''true''' or '''false''' value if the error checking function that was called was detected no errors or detected an error. But let's stick to some simple examples first, before tackling more complex use of functions.<br><br>
:#Let's create a function that '''returns''' some data after the function is called. This function does not print out any text: instead; it creates new variables and at the end returns the value of one of the variables.<sourcelang="python">
def return_text_value():
name = 'Terry'
return greeting
</source>
:# Call the function in your ipython3 shell by issuing the followinglike this:<sourcelang="python">
return_text_value()
</source>One major difference between a function '''returning a value''' and simply '''printing a value''' is that '''returned''' values can be caught and stored in variables used in the program (that called the function) for later use. Once the returned value has been stored, it can be printed, manipulated, compared in IF statements, etc. Below will cover how to store a returned value.<br><br>
:#Enter Notice that this syntax looks just the following call to the input() function which you've used in the ipython3 shell to see returning a variable's value workslast lab:<sourcelang="python">
text = return_text_value()
</source>
:#Now the returned text from the function has been stored in the variable "'''text'''". It can be used like any string value now.<sourcelang="python">
print(text)
</source>
:'''Perform the Following steps:'''
:#Issue Define the following in your ipython3 shellreturn_number_value() function:<sourcelang="python">
def return_number_value():
num1 = 10
</source>
:#Now, issue the following in the ipython3 shell to And call the '''return_number_value()''' functionit:<sourcelang="python">
number = return_number_value()
print(number)
print(return_number_value() + 10)
</source> What do you notice?<br><br>
:#Now, issue the following which use the print() statement to display both strings and numbers:<sourcelang="python">
number = return_number_value()
print('my number is ' + number)
</source> What do you notice? You should notice a warning message. This occurs because the returning value is a '''number''' and NOT a '''string'''! Combining numbers and strings in a statement (such as '''print()''') can cause errors. The error message should appear similar to the one displayed below: <source>
</source>
:#If a number needs to be combined with a string, use the '''str()''' predefined function that was discussed in a previous lab in order to convert the returned number into a string:<sourcelang="python">
number = return_number_value()
print('my number is ', number)
'''Creating a Python Script'''
:Now it's time to create a Python script that uses two functions. One function does not return returns a string value and is simply used (when called) to greet the user, where the other function returns the result of adding two values (stored in variables within the function).
:'''Perform the following Instructions:'''
:::*Add another '''empty line''' following by the '''return_number_value()''' function '''definition''' that you previously entered in the shell.
:::*Add a '''couple of empty lines''', following by a comment stating: '''# Main Program'''
:::*Add another '''couple of empty lines''', followed by the statements displayed below:<sourcelang="python">
if __name__ == '__main__':
print('python code')
print(str(number))
</source>
:::2. Run Running your lab3a.py script in your ipython3 shell by issuing:<source>run lab3a.py</source>You program you should have seen three lines being displayed: the text "python code", a greeting, and a result of a math calculation. The '''if''' statement in the code above is a special '''if''' statement needed to make sure that your "main" code only runs when you want it to. More on that later.
'''Importing Functions From other Python Scripts'''
In order to use functions from other scripts, you use the '''import''' command.<br><br>We can demonstrate the use of re-using functions from another script by simply '''issuing statements from the ipython shell to call a function from your lab3a.py Python script'''. But care MUST be taken to first use the import command to load in the function declarations from your Python script to your ipython shell environment firststatement.<br><br>
text = lab3a.return_text_value()
</source>You should notice an error indicating '''"name 'lab3a' is not defined"'''. This error occurs since you failed to instruct the ipython shell python to '''import''' or "load existing defined functions from your lab3a.py script" to '''internal memory'''.<br><br>:# Issue the following within the ipython shellModify your program like this:<sourcelang="python">
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. '''NOTE:''' since you are in the ipython shell, the import command only will work as long as you are '''logged into that shell'''. You will need to use other methods (contained in other Python Scripts (or future ipython shell sessions) to make these function imports '''persistent''', but you will learn about that at a later time.<br><br>:# Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<sourcelang="bash">
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
<br><br>
= INVESTIGATION 2: CREATING ADVANCED FUNCTIONS WITH ARGUMENTS AND RETURN VALUES =
== PART 1 - Providing Functions With Arguments ==
:'''Perform the Following Steps:'''
:#Start the ipython3 shellCreate a new Python file for testing.:<source>ipython3</source>#When passing arguments to functions, you put data such as '''strings''', '''numbers''', or '''variable names''' within brackets immediately following the function name.<br><br>'''NOTE:''' If a function accepts arguments, then those rguments arguments must be declared (using variable names) when the function is declared. Those declared variable names are then used within the function for processing. Also, when you call a function with arguments, the number of arguments passed up to the function must match the number of arguments that were specified in the function declaration.<br><br>:#Issue the following from the ipython shell to declare Define a function called '''square()''':<sourcelang="python">
def square(number):
return number ** 2
</source>'''FYI:'''You may have learned that you multiple a number by itself in order to "square" the number. In python, the '''**''' operator will raise the operand on the left to the power of the operand on the right.<br><br>When calling functions with multiple arguments, the arguments are separated by '''commas'''. See what happens if you provide strings, strings without using quotes, or numbers with decimals in the following examples.
:#Issue the following to test Test your '''square()''' function:<sourcelang="python">
square(5)
square(10)
square(square(2))
square('2')
</source>Notice that nothing is printed, you need to print the values the functions return to see what they are.:#The last function call should produce an '''error message'''. This is caused by sending a '''string''' instead of a number that is processed by the function. We could use the int() function to convert any value passed in as a string by mistake to an integer number.<br><br>:#Issue the following to declare Declare the function '''sum_numbers()''':<sourcelang="python">
def sum_numbers(number1, number2):
return int(number1) + int(number2)
</source>
:#Issue the following from the ipython shell Call that function to see what happens:<sourcelang="python">
sum_numbers(5, 10)
sum_numbers(50, 100)
</source>
:#Issue the following to issue You can also do what looks like calling a function within another function, but it's actually just calling sum_numbers() first, then calling square() with the return from sum_numbers as an argument:<sourcelang="python">
square(sum_numbers(5, 5))
</source>'''NOTE:''' Running functions with multiple arguments is the same. When you put call a function as a an argument of another function, the '''inner-most function will run first''', and the return the value '''10''' from the that will be used as the argument for the '''outer function'''. In the example below, '''sum_numbers(5, 5)''' will return '''10''', thus providing that result to be square with that value '''square(10)'''.<br><br>
'''Practice Creating a Function that Accepts Arguments and Returns a Value'''
:::'''Python Script Template'''
:::<sourcelang="python">#!/usr/bin/env python3
def sum_numbers(number1, number2):
if __name__ == '__main__':
print(sum_numbers(10, 5))
print(subtract_numbers(10, 5))
::*The script should contain no errors
::'''Sample Run:'''<sourcelang="python">run ./lab3b.py
15
5
50
</source>
::'''Sample Run Using importOther examples:'''<sourcelang="python">
import lab3b
lab3b.sum_numbers(10, 5)
# Will return 15
lab3b.sum_numbers(25, 25)
# Will return 50
lab3b.subtract_numbers(10, 5)
# Will return 5
lab3b.subtract_numbers(5, 10)
# Will return -5
lab3b.multiply_numbers(10, 5)
# Will return 50
lab3b.multiply_numbers(10, 2)
# Will return 20
</source>
::2. Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<sourcelang="bash">
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
</source>
::3. Before proceeding, make certain that you identify any and all errors in lab3b.py. When the checking script tells you everything is OK before proceeding - proceed to the next step.
'''Passing up Multiple Arguments and Using Logic Conditional Statements'''
:You will now create a more complex function that will not only pass-up arguments, but also include '''logic''' to control the direction (flow) of the function, and affect how your Python script will be run. You will create a function that uses an '''if/elif/else''' logic statement.
:'''Perform the Following Steps:'''
:#Start the ipython3 shell<source>ipython3</source>:#Define Use a temporary Python file to define the following function in your ipython shell:<sourcelang="python">def check_temperaturedescribe_temperature(temp):
if temp > 30:
return 'hot'
return 'ok'
</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.
:#Issue the following functions (with arguments) Call describe_temperature like this to confirm the results:<source>check_temperatureprint(describe_temperature(50))# Will return 'hot'check_temperatureprint(describe_temperature(20))# Will return 'perfect'check_temperatureprint(describe_temperature(-50))# Will return 'cold'check_temperatureprint(describe_temperature(25))# Will return 'ok'check_temperatureprint(describe_temperature(10))# Will return 'ok'
</source>
'''Create a Python Script Using an Advanced FunctionReceiving Multiple Arguments'''
:'''Perform the Following Instructions:'''
:#Create the '''~/ops435/lab3/lab3c.py''' script. The purpose of the script is to make 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 the functionit. If the operate function does NOT understand the operator given, it should return a an error message(e.g. calling the function to 'divide' two numbers).:#Use this template to get started:<sourcelang="python">
#!/usr/bin/env python3
print(operate(10, 5, 'subtract'))
print(operate(10, 5, 'multiply'))
print(operate(10, 5, 'divide'))
</source>
:::*The operate() function should use '''logicconditional''' statements<br> '''FYI:''' Remember that you MUST consistently '''indent ALL code''' for within each logic section (or test): otherwise, it may not allow the logic statement to work correctly. :::*The operate() function should accept '''three arguments'''.:::*The operate() function should '''return''' the result.:::*The operate() function should '''return''' an error message if the operation is unknown<br> '''FYI:''' Use single quotes or double-quotes to return pass a string value. You should be able to use double quotes within the message as shown in the sample runs.:::*The script should contain show the exact output as the sample imports.:::*The script should contain no errors.:::*As an extra exercise, try to write your function with only one return statement.
:::'''Sample Run 1:'''<source>
15
5
</source>
:::'''Sample Run 2 (with using importfrom another Python file):'''<source>
import lab3c
lab3c.operate(10, 20, 'add')
# Will return 30
lab3c.operate(2, 3, 'add')
# Will return 5
lab3c.operate(100, 5, 'subtract')
# Will return 95
lab3c.operate(10, 20, 'subtract')
# Will return -10
lab3c.operate(5, 5, 'multiply')
# Will return 25
lab3c.operate(10, 100, 'multiply')
# Will return 1000
lab3c.operate(100, 5, 'divide')
# Will return Error: function operator can be "add", "subtract", or "multiply"
lab3c.operate(100, 5, 'power')
# Will return Error: function operator can be "add", "subtract", or "multiply"
</source>
:::3. Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<sourcelang="bash">
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
ls CheckLab3.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab3.py
python3 ./CheckLab3.py -f -v lab3c
</source>
:::4. Before proceeding, make certain that you identify any and all errors in lab3c.py. When the checking script tells you everything is OK before proceeding - proceed to the next step. ::Make notes for all of your observations in your lab log book, and proceed to Part 2.
<br><br>
== PART 2 - Running System Commands with Subprocess ==
:The remainder of this lab investigation will allow you to run operating system commands via your Python script. Although there are different ways in which to issue operating system commands, you will learn how to issue two of them within a Python script to run in a secure manner regardless of the type of operating system platform (eg Linux, Windows, MacOSX).
'''Perform the Following Steps:'''
:#Start Create a new python file for testing.:#Import the ipython3 shell'''''os''''' module in your python file.:<source>ipython3</source> #You can issue operating system commands by using the '''system()''' function.<br><br>:#Issue the following in ipythonTry it:<sourcelang="python">os.system('ls')os.system('whoami')os.system('ifconfig')</source> You should notice Notice that the output from the programs is printed in your the Linux commands script. Consider that may not always be what you issuedwant.<br><br>:#Issue the following in ipythonTry this also:<sourcelang="python">os.system('ipconfig')</source>You should notice an error message: ''''ipconfig : command not found''''. That error occurs since that command was an MS Windows command, and our current platform is Linux.<br><br>It is not usually always a good idea to run system commands in Python, this makes your Python code less portable and makes it require a specific operating system or a system that has those commands available. Also, allowing python to execute commands on the operating system can be a '''security problem'''. For these reasons You should think about that when you decide whether you should only or should not use '''sub-process''' and '''a system commands''' as a last resort and command to accomplish some task or stick to pure Python code only.<br><br>As you may recall from lab2, you issued '''import sys''' to import special variables from the system. You can import a subprocess in order to run common non OS specific commands securely.<br><br>:#Issue Import the following subprocess module in ipython:<source>import subprocess</source>your python file.:#To view the available modules and attributes to obtain non OS specific command-like information, issue the following:<source>dir(subprocess)</source>There are many available modules and attributes features available as part of the subprocessmodule, we are interested in "'''Popen'''". This method subprocess.Popen() can be used to run system commands as a child process to the Python script. This The code below output will create a new child process, in Python we can control this through the new Python object we just created, "'''p'''". "'''p'''" now has a collection of methods(functions that are apart of a object) available, view them with '''dir()'''.<br><br>:#To demonstrate, issue the following:<sourcelang="python">
p = subprocess.Popen(['date'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
# The above stdout is stored in bytes
# Convert stdout to a string and strip off the newline characters
stdout = stdoutoutput[0].decode('utf-8').strip()print(stdout)
</source>
:#While many of these system commands could Sometimes you will be instead written in simply Pythonable to use purely python code to get your job done, the exercise of running but often you will need to call existing system commands is . It's importantto learn how to call them and how to interact with those external processes.
'''Practice Running System Commands From Python'''
:'''Perform the Following Instructions:'''
9.6G
</source>
import lab3d
lab3d.free_space()
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
ls CheckLab3.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab3.py
python3 ./CheckLab3.py -f -v lab3d
</source></li>:::4. <li>Before proceeding, make certain that you identify any and all errors in lab3d.py. When the checking script tells you everything is OK before proceeding - proceed to the next step. Make notes for all of your observations in your lab log book, and proceed to INVESTIGATION 3.<br/li><br/ol>
= 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:<sourcelang="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:<sourcelang="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 provide You can also retrieve ranges of items in from a list(these are called slices): <sourcelang="python">print(list1[0:5] ) # Starting with index 0 and stopping before index 5print(list2[2:4] ) # Starting with index 2 and stopping before index 4print(list3[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>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>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 from existing lists to create new lists. To demonstrate, issue the following:<source>first_only_list = [ list1[0], list2[0], list3[0] ]first_only_list
</source>
:#Create a Python script called: '''~/ops435/lab3/lab3e.py'''<br>The purpose of this script is to have a number of functions that output a different data storage in various elements of a list. Each function will return either a single item from the list OR will create a new list and return the entire new list.<br><br>
:#The template function names and the special if statement:<sourcelang="python">
#!/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())
:::'''Additional Requirements'''
:::*The script should have declare a list called '''my_list''' created BEFORE any function definition:::*The list called '''my_list''' should have the values: '''100''', '''200''', '''300''', and ''''six hundred'''':::*The script should have a function called '''give_list()implement''' which '''returns''' a list:::*The script should the empty functions - i.e. you have a function called '''give_first_item()''' which '''returns''' a string:::*The script should have a function called '''give_first_and_last_item()''' which '''returns''' a list:::*The script should have a function called '''give_second_and_third_item()''' which '''returns''' a listto fill in the bodies for these functions
:::'''Sample Run 1:'''<source>
[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
ls CheckLab3.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab3.py
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. ::Make notes for all of your observations in your lab log book, and proceed to Part 2.
== PART 2 - Manipulating Items in Lists ==
:'''Perform the Following Steps:'''
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>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:<sourcelang="python">help(courses.append)
courses.append('ops235') # Add a new item to the end of the list
print(courses)
courses.insert(0, 'hwd101') # Add a new item to the specified index location
print(courses)
courses.remove('ops335') # Remove first occurrence of value
print(courses)
sorted_courses = courses.copy() # Create a copy of the courses list
</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:<sourcelang="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 '''index()''' function allows searching inside a list for a value, it will return the index number of the first occurence. <source>fit on one screen:number = 10helpprint(list_of_numbers.index)list_of_numbers.index"List length is " + str(numberlength_of_list) # 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 a logic 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>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 (a "determinant" 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 The following '''for''' loop works. The for loop will store data the value of each element from list_of_numbers within a temporary variable (in the demonstration below, the variable called: named '''item''') and run code that are indented below the loop for loop. This operation will repeat until ALL contained items within the list have been usedeach item.<br><br>:#Issue the following in the ipython shellRun this from a temporary Python file:<sourcelang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
for item in list_of_numbers:
print(item)
</source>
:#Instead As you can see: instead of writing eight function calls for each element of re-calling functions over and overthe list, we can use them call the function in a loop. When combined with using lists, this is a very efficient method And we won't have to rewrite code if the length of processing large volumes of datathe list changes.<br><br>:#Issue Run the followingcode:<sourcelang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
def square(num):
return num * num
print(square(value))
</source>You should see from the previous demonstration the advantage of using lists with functions. Although useful, the demonstration The code above only prints the squares as opposed to saving and does not save them for future use. The next demonstration example uses a function that loops through listslist, squares the values, but and also saves the squares in a new list.<br><br>:#Issue Run the followingcode:<sourcelang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
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, powerful, 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, issue run the followingcode:<sourcelang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
def delete_numbers(numbers):
numbers.remove(5)
delete_numbers(list_of_numbers)
print(list_of_numbers)
</source>
:'''Perform the Following Instructions:'''
:#Create the '''~/ops435/lab3/lab3f.py''' script. The purpose of this script is to use functions to modify items inside a list. <sourcelang="python">
#!/usr/bin/env python3
def add_item_to_list(my_listordered_list): # Appends new item to end of list which is with the value (last item + 1)
def remove_items_from_list(my_listordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
# Main code
if __name__ == '__main__':
print(my_list)
remove_items_from_list(my_list, [1,5,6])
print(my_list)
</source>
'''Additional Requirements'''
:::*The missing list '''my_list''' should have the values: '''1, 2, 3, 4, 5''':::*The script program should have a function called '''add_item_to_list(my_listordered_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(my_listordered_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
ls CheckLab3.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab3.py
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. ::Make notes for all of your observations in your lab log book, and proceed to INSTRUCTOR SIGN-OFF.
= LAB 3 SIGN OFF (SHOW INSTRUCTOR) =
::<span style="color:green;font-size:1.5em;">✓</span> Output of: <code>./CheckLab3.py -f -v</code>
::<span style="color:green;font-size:1.5em;">✓</span> Output of: <code>cat lab3a.py lab3b.py lab3c.py lab3d.py lab3e.py lab3f.py</code>
::<span style="color:green;font-size:1.5em;">✓</span> Lab3 logbook notes completed'''Be able to answer any questions about the lab to show that you understood it!'''
<br><br>
= Practice For QuizzesLAB REVIEW = :# What is the purpose of using functions in a Python script?:# Write Python code to define a function called '''greetings()''' that when called will greet the user by name and on the next line display the current date:# Why is it useful for functions to accept '''arguments''' passed-up upon function execution?:# What is the purpose of the '''import''' command? What can be the consequence if the import command is not used prior to running a function by name?:# Write Python code to define a function called '''join()''' that excepts two arguments which will be be stored as the variables called '''word1''' and '''word2''' respectively during the execution of the function.:# What is the command to return a value from a function?:# What is the purpose of the '''system()''' function?:# What is the purpose of a '''list'''?:# Assume that the following list has been defined: '''mylist = [ 'apple', 1, 'grape', 2, 'banana', 3, ]'''<br>Based on that, what will the following contain?<source lang="python">mylist[0]mylist[3]mylist[-1]mylist[0:1]</source>:# Assume that the following list has been defined: '''combined_list = [ [7, 5], ['x', 'y'], [ 5, 'f' ] ]'''<br>Based on that, what will the following contain?<source lang="python">combined_list[0]combined_list[1]combined_list[1][0]combined_list[2][0:2]</source>:# Briefly explain the purpose of each of the following functions (methods) that can be used with lists: '''append''', '''insert''', '''remove''', Tests'''sort''', Midterm & Final Exam '''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>:# Write a Python script to display all of the elements within a simple list.
[[Category:# x:# x:# xOPS435-Python]]