Changes

Jump to: navigation, search

OPS435 Python Lab 2

45 bytes added, 20:25, 13 January 2019
PART 2 - Arguments
== PART 2 - Arguments ==
:An argument is a value data item that is passed to a program or passed to a function that can be used for processing within that program or function. In the previous section, you passed an argument to the '''input()''' function. In this section, you will learn how to pass an argument to your Python script, but this time, this argument will be passed when we execute your Python script from the bash shell.
'''Perform the following steps:'''
:#Use a temporary file for testing your work for this section.
:#In order to read arguments in Python, we will need to '''import special objects''' from the system. This is a standard 'library' of code provided by the developers of Python. By issuing '''import sys''', you have loaded code written by another person, each 'library' that gets loaded will give us extra functionality and objects to our program.<br><br>
:#Start with the following line to import special additional python objects:<source>
import sys
</source>
:#Call the following functions and note what they do:<source lang="python">
print(sys.version) # tells us our the version of the python versioncurrently in use
print(sys.platform) # tells us our operating system platform
print(sys.argv) # tells us our arguments or shell version if issued from shell
print(len(sys.argv)) # tells us the number of command line arguments the user provide issued from shell
sys.exit() # will immediately end the running Python script, ignoring the remaining lines in the Python script
</source><br>Instead of using the '''input()''' function to prompt the user for data, we can use the '''sys.argv''' <b>list object </b> to store data as a result of running the Python script with arguments. The list object '''sys.argv''' list object, when used within your Python script can store the following:<ul><li>'''sys.argv''' - stores all argument items</li><li>'''sys.argv[0]''' - stores the name of the script/program</li><li>'''sys.argv[1]''' - stores the first argument</li><li>'''sys.argv[2]''' - stores the second argument</li><li>etc...</li><li>'''len(sys.argv)''' - gives the number of arguments</li></ul><br>
:#Create a new script called '''~/ops435/lab2/showargs.py''' and add the following content:<source lang="python">
#!/usr/bin/env python3
1,760
edits

Navigation menu