Changes

Jump to: navigation, search

OPS435 Python3 Lab 3

949 bytes added, 19:14, 28 February 2020
m
INVESTIGATION 1: CREATING SIMPLE FUNCTIONS: fix typo
[[Category:OPS435-Python]][[Category:rchan]]
= <font color='red'>Still under Construction - Please do not use</font> =
= LAB OBJECTIVES =
:In this lab, you will learn how to identify and create different types of '''functions''', study the properties of '''list objects''' and learn how to manipulate them using their built-in methods, and finally we will explore how '''loop''' can be used to reduce code repetition.
:Write Python code in order to:
:*'''Create and use Call built-in and user created functions''' - using the '''def''' and '''import''' keywordsto create and use user defined functions, understand the '''None''' keyword, study the '''os.system()''', '''os.popen()''', and '''subprocess.Popen()''' functions
:*'''Obtain properties and manipulate list object''' - using the built-in function: len(), min(), max(), and list object methods: copy(), sort(), append(), insert(), and remove()
:*'''Looping through lists''' - Looping (iteration) is the method of using loop to process items in a list object one at a time using the same code to reduce code repetition in your Python script. This will result in a better, more efficient and effective program execution.
:Usually, a '''function''' contains '''programming code''' and most likely placed near the top of a python file, and before the main processing section.
: When a Python program is run, the '''function's code is read into the corresponding process memory''', waiting to be executed when the function is called. Until a Function is specifically called, its code will sit still in the memeorymemory.
:When creating programs that define and use functions, '''a large programming task can be broken-down into smaller elements''' (or '''modules'''). This is why creating programs that use functions is referred to as '''"modular programming"'''.
:#Create a new python file for testing code in this section.
:#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, and it should be followed first by the name of the function, and secondly arguments (if there is any) it expected, and finally a ":". When the python interpreter see the function declaration and its code, it does not run the code you write right wary. Functions, just like '''if''' statements, must have all code under them indented.<source lang="python">
def hello():
print('Hello World')
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 wayOn one hand, that is OK. On the other hand, you may want to create and use a function to do somethinguseful, like perform error checking or some other task that report something back to the '''caller''' for further processing. For example, return a '''true''' or '''false''' value if the by an error checking function that was called was detected no errors or detected to check where there is an error. But let's stick to some simple examples first, before tackling more complex use of functions. In Python, when a function does not return a value, it the Python interpreter will automatically return a special Python object called '''None'''. '''None''' is a Python 3.x keyword which is used to indicate that there is "nothing". 'None' is not the same as an empty object, like an empty string. Let update the above Python script to the following version:<source lang="python">
def hello():
print('Hello World')
my_stuff = hello()
print('Stuff return from hello():',my_stuff)
print('the object my_stuff is of type:',type(my_stuff))</source>You can assume that there is a hidden '''return''' statement at the end of any function if it does not have on one implicitly.The following python script should produce that the same result as the one above:<source lang="python">
def hello():
print('Hello World')
print('Inside a Function')
return
my_stuff = hello()
print('Stuff return from hello():',my_stuff)
print('the object my_stuff is of type:',type(my_stuff))
</source><br><br>
== PART 2 - Function that does not take argument but returns a string ==
:#Let's create a function that '''returns''' some data to the caller after the function is called. This function does not print out any text: instead; it creates new objects and at the end , returns one of the object named '''greeting''', which is a string object containing 'Good Monring Terry'.<source lang="python">
def return_text_value():
name = 'Terry'
text = return_text_value()
</source>
:#Now the returned string from the function has been assigned to an object named "'''text'''". It can be used like any string object now.<source lang="python">
print(text)
</source>
print(text)
lab3a.return_number_value()
</source> You should notice that although your script runs without any error, however, it only prints out text returned from the return_text_vaule() function. It does not print out the value returned from the return_number_value() function. Modify the last line like this:<source lang="python">import lab3atext = lab3a.return_text_value()print(text)print(lab3a.return_number_value())</source> You should see the values retuned form all of the function calls should now work.
:# Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab3/
def square(number):
return number ** 2
</source>'''FYI:'''You may have learned that you multiple multipley 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, which will give the same result as muliple muliplying the number by itself.<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.
:#Test your '''square()''' function:<source lang="python">
def square(number):
<br><br>
== PART 2 - Launching Linux command and controlling its process Commands with builtin functions in os and subprocess modules ==:The remainder of this investigation will allow you to explore the behaviour of some functions from the os and subprocess modules. All of these functions will take function argument(s), some will return value(s), and some will not. The functions we are going to explore are: os.system(), os.popen(), and subprocess.Popen(). All of them can be used to launching launch any Linux commands and can interact with the their processesvia the standard input, standard output, and standard error data channels.
'''Perform the Following Steps:'''
import os
whoami_return=os.popen('whoami')
whocmi_contents whoami_contents = whoami_return.read()
print('whoami_contents:',whoami_contents)
</source>What conclusion would you draw from the about python script?
:#Try another one:<source lang="python">
ipconfig_return = os.popen('ipconfig')
ipconfig_contents = ipconfig_return.read()print('The contents of ipconfig_return:',ipconfig_returnipconfig_contents)
</source>
<br><br>As you may recall from lab2, you issued '''import sys''' to import special object from that built-in module. You can also import the subprocess module to load a function called '''Popen()''' which will allow you to have better control of the output produce by Linux commands like 'ls', 'whoami', and 'ifconfig', etc. <br><br>
:# 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. [hint: use the os.system() function to 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 declare a function called '''join()''' that excepts accepts 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()''' functionin the os module?:# What is the purpose of a '''list'''object?
:# 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]
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''', '''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>
:# Write a Python script to display all of the elements within items in a simple list, one item per line[[Category:OPS435-Python]]

Navigation menu