Difference between revisions of "OPS435 Python Lab 2"

From CDOT Wiki
Jump to: navigation, search
(PART 2 - Arguments)
 
(200 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 +
<font color='red'>
 +
'''** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **'''
 +
</font>
 
= LAB OBJECTIVES =
 
= LAB OBJECTIVES =
  
Line 7: Line 10:
 
:Write Python code in order to:
 
:Write Python code in order to:
  
:*'''Accept information from users''' that run a Python script, such as a username or password.
+
:*'''Accept data from users''' that run a Python script, such as a username or password.
  
:*'''Process the inputted information''' using '''Logic Statements'''.
+
:*'''Process the inputted data''' using '''Conditional Statements'''.
:::This means that the program will completely change how it works based on the input given, an example would be, providing the correct password or providing the wrong password.
+
:::This means that the program will change how it behaves based on the input given, an example would be, providing the correct password or providing the wrong password.
  
:*'''Process the inputted information''' using '''Looping Statements'''.
+
:*'''Process the inputted data''' using '''Looping Statements'''.
:::Looping (iteration) is the ability for your program to repeatedly run the same code over and over. An example of this, could be found when you provide the incorrect password to a login page and it responds with, 3 attempts to login remaining.
+
:::Looping (iteration) is the ability for your program to repeatedly run the same block of codes over and over. An example of this, could be found when you provide the incorrect password to a login page and it responds with, 3 attempts to login remaining.
 
<br><br>
 
<br><br>
 +
 
= INVESTIGATION 1: USER INPUT =
 
= INVESTIGATION 1: USER INPUT =
  
 
== PART 1 - User Input ==
 
== PART 1 - User Input ==
:In this section, you will learn how to prompt (ask) the user running the program for input or data. Although you will not be immediately be using the information that the user provided, you will use that information later in this lab to change how a Python script works under different situations.
+
:In this section, you will learn how to prompt (ask) the user running the python script for input or data. Although you will not be immediately be using the data that the user provided, you will use that data later in this lab to change how a Python script works in different situations.
  
'''Storing User Input In Variables'''
+
'''Storing User Input data to Python objects'''
  
 
:'''Perform the following steps:'''
 
:'''Perform the following steps:'''
:#Launch your Centos VM, open a shell terminal (as a regular user) and start a new ipython3 session:<source>
+
:#Launch your Centos VM, open your code editor, and a a shell terminal (as a regular user) for executing your code.
ipython3
+
:#To begin, let's start out with a very basic script. This script will use objects that will display specific values to your terminal. Create the file '''lab2a.py''' in your '''~/ops435/lab2''' directory, containing the following content:<source lang="python">
</source>
 
:#To begin, let's start out with a very basic script. This script will use variables that will display specific information to your terminal. Move to your '''~/ops435/lab2''' directory, create the file '''lab2a.py''' with a text editor containing the following content:<source>
 
 
#!/usr/bin/env python3
 
#!/usr/bin/env python3
  
Line 33: Line 35:
 
print('Hi ' + name + ', you are ' + str(age) + ' years old.')
 
print('Hi ' + name + ', you are ' + str(age) + ' years old.')
 
</source>
 
</source>
:#Try running this script inside ipython3 and study the output:<source>
+
:#Try running this script and study the output:<source>
run lab2a.py
+
./lab2a.py
</source>This Python script is not very useful: it displays the same output regardless of the number of times that the Python script is run.<br>The '''input()''' function is used to obtain information from the user and store it into a variable. It is recommended to place a question (or hint) as a argument in the input() function: this will aid the user in typing in the correct information.<br><br>
+
</source>This Python script is not very useful: it displays the same output regardless of the number of times that the Python script is run.<br>The '''input()''' function is used to obtain information from the user and store it into an object (also called a variable). It is typical to place a question (or hint) as a argument in the input() function: this will aid the user in typing in the correct data.<br><br>
:#Return to your '''ipython3''' shell and type the following code (do '''NOT''' edit the lab2a.py file, just issue from the shell): <source>
+
:#Replace the print() call in your lab2a.py with the following (you can just comment-out the print() call using a '''#''' at the beginning of the line): <source lang="python">
 
colour = input("Type in a colour and press enter: ")
 
colour = input("Type in a colour and press enter: ")
 
</source>
 
</source>
 
:#When prompted, type the text: '''red''' and press ENTER. Did anything display? Why not?
 
:#When prompted, type the text: '''red''' and press ENTER. Did anything display? Why not?
:#Issue the following in the ipython3 shell:<source>print(colour)
+
:#Add another line to your script:<source lang="python">print(colour)
 
</source>What was displayed?
 
</source>What was displayed?
:#Issue the following in the ipython3 shell:<source>print('The colour I typed in is: ' + colour)
+
:#Now replace that line with this:<source lang="python">print('The colour I typed in is: ' + colour)
 
</source>Note what was displayed.
 
</source>Note what was displayed.
:#Exit the ipython3 shell, download the check script and check your work. Enter the following commands from the bash shell.<source>
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2a
 
</source>
 
:#Before proceeding, make certain that you identify any and all errors in '''lab2a.py'''. When the check script tells you everything is '''ok''' before proceeding to the next step.
 
  
''' Practice Storing User Input '''
+
''' Practice Storing User Input data '''
  
:Now it's time to create a new script to prompt the user to enter data and display that data on their terminal. Refer to variable name and prompt text information when creating your Python script. Refer to Sample Runs displayed below for exact prompt and output requirements.
+
:Now it's time to create a new script to prompt the user to enter data and display that data on their terminal. Refer to object name and prompt text information when creating your Python script. Refer to Sample Runs displayed below for exact prompt and output requirements.
  
 
:'''Perform the following Instructions:'''
 
:'''Perform the following Instructions:'''
Line 64: Line 59:
  
 
:::*The script should have a '''Shebang line'''
 
:::*The script should have a '''Shebang line'''
:::*The script should use a variable called '''name'''
+
:::*The script should use an object called '''name'''
:::*The script should use a variable called '''age'''
+
:::*The script should use an object called '''age'''
 
:::*The script should prompt the user for "Name: "
 
:::*The script should prompt the user for "Name: "
 
:::*The script should prompt the user for "Age: "
 
:::*The script should prompt the user for "Age: "
:::*The script should store the values in the correctly spelled variables (case sensitivity counts)
+
:::*The script should store the values in the correctly spelled objects (case sensitivity counts)
 
:::*The script should print the EXACT OUTPUT as shown (case sensitivity counts)
 
:::*The script should print the EXACT OUTPUT as shown (case sensitivity counts)
  
 
:::'''Sample run 1:'''<source>
 
:::'''Sample run 1:'''<source>
run lab2b.py
+
./lab2b.py
 
Name: Jon
 
Name: Jon
 
Age: 20
 
Age: 20
Line 78: Line 73:
 
</source>
 
</source>
 
:::'''Sample run 2:'''<source>
 
:::'''Sample run 2:'''<source>
run lab2b.py
+
./lab2b.py
 
Name: Jen
 
Name: Jen
 
Age: 25
 
Age: 25
 
Hi Jen, you are 25 years old.
 
Hi Jen, you are 25 years old.
 
</source>
 
</source>
:::3. Download the check script and check your work. Enter the following commands from the bash shell.<source>
+
:::3. Download the checking script and check your work. Run the following commands from the bash shell.<source lang="bash">
 
cd ~/ops435/lab2/
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
+
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2b
 
python3 ./CheckLab2.py -f -v lab2b
 
</source>
 
</source>
Line 92: Line 87:
  
 
== PART 2 - Arguments ==
 
== PART 2 - Arguments ==
:An argument is a value 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.
+
:An argument is a 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
+
'''Perform the following steps:'''
  
:#In order to read arguments in Python, we will need to import special variables from the system. This is done very easily.<source>
+
:#Use a temporary file for testing your work for this section.
ipython3
+
:#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 additional python objects:<source>
 
import sys
 
import sys
</source>
+
</source>  
:#This is a standard 'library' of code provided by the developers of Python. By typing 'import sys' we have loaded code written by another person, each 'library' that gets loaded will give us extra functionality in our program.
+
:#Call the following functions and note what they do:<source lang="python">
:#To inspect this library and look at all that it contains we can use the 'dir()' function. This can be used to inspect any library(and more) looking at all the functions and values contained within.<source>
+
print(sys.version) # tells us the version of the python currently in use
dir(sys)
 
</source>
 
:#Now don't feel overwhelmed, this will provide a lot of information, but we can also get some hints at the different information this library provides. <source>
 
print(sys.version) # tells us our python version
 
 
print(sys.platform) # tells us our operating system platform
 
print(sys.platform) # tells us our operating system platform
print(sys.argv) # tells us our arguments
+
print(sys.argv) # tells us our arguments or shell version if issued from shell
sys.exit() # will immediately end our script when run
+
print(len(sys.argv)) # tells us the number of command line arguments the user provide issued from shell
</source>
+
sys.exit() # will immediately end the running Python script, ignoring the remaining lines in the Python script
:#The 'sys.exit()' will immediately end the script on the line it is called, no other line in the script will ever be run. This function will be useful later in this lab, make sure you write it down in your notes.
+
</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''', 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 '~/ops435/lab2/showargs.py' and place the following content inside<source>
+
:#Create a new script called '''~/ops435/lab2/showargs.py''' and add the following content:<source lang="python">
 
#!/usr/bin/env python3
 
#!/usr/bin/env python3
  
Line 121: Line 113:
 
print('Print out ALL script arguments: ', arguments)
 
print('Print out ALL script arguments: ', arguments)
 
print('Print out the script name: ' + name)
 
print('Print out the script name: ' + name)
 +
print('Print out the number of argument: ', len(sys.argv))
  
 
</source>
 
</source>
:#Run the script and examine the output:<source>
+
:#Run the script and examine the output by running the Python script without and with arguments:<source>
run showargs.py
+
./showargs.py
run showargs.py testing different arguments
+
./showargs.py testing different arguments
run showargs.py argument1 argument2 argument3
+
./showargs.py argument1 argument2 argument3 argument4
 
</source>
 
</source>
:#The 'sys.argv' contains all arguments, 'sys.argv[0]' contains the name of the script/program, 'sys.argv[1]' contains the first argument, 'sys.argv[2]' contains the second argument.
 
  
 
''' Practice Using Arguments '''
 
''' Practice Using Arguments '''
:#Now it's time to create a new script. Make a copy of '''lab2b.py''' and call it '''lab2c.py'''. Now modify '''lab2c.py''' so that it uses 'sys.argv[1]' and 'sys.argv[2]' instead of the input() functions. Example output is shown below:
+
:Now it's time to create a new script, but unlike prompting the user for data, the data (as arguments from running your Python script) will be used instead. Refer to variable name and prompt text information when creating your Python script. Refer to Sample Runs displayed below for exact prompt and output requirements.
 +
 
 +
:'''Perform the following Instructions:'''
 +
 
 +
:#Make a copy of '''lab2b.py''' and call it '''lab2c.py'''.
 +
:#Modify '''lab2c.py''' to use the '''sys.argv[1]''' and '''sys.argv[2]''' functions instead of the '''input()''' function (used in your previous ''lab2b.py'' script).
 +
 
 +
:::'''Input / Output Requirements'''
 +
 
 +
:::*The script should have a '''Shebang line'''
 +
:::*The script should contain '''import sys'''
 +
:::*The script should use a variable called '''name'''
 +
:::*The script should use a variable called '''age'''
 +
:::*The script should use '''sys.argv[1]''' (first argument)
 +
:::*The script should use '''sys.argv[2]''' (second argument)
 +
:::*The script should store the values in the correct variables (including case sensitivity)
 +
:::*The script should print the EXACT OUTPUT as shown (including case sensitivity)
  
::*The script should have a Shebang line
+
:::'''Sample run 1:'''<source>
::*The script should import sys
+
./lab2c.py Jon 20
::*The script should use a variable called "name"
 
::*The script should use a variable called "age"
 
::*The script should use sys.argv[1] (first argument)
 
::*The script should use sys.argv[2] (second argument)
 
::*The script should store the values in the correct variables
 
::*The script should print the EXACT OUTPUT as shown
 
:::Sample run 1:<source>
 
run lab2c.py Jon 20
 
 
Hi Jon, you are 20 years old.
 
Hi Jon, you are 20 years old.
 
</source>
 
</source>
:::Sample run 2:<source>
+
:::'''Sample run 2:'''<source>
run lab2c.py Jen 25
+
./lab2c.py Jen 25
 
Hi Jen, you are 25 years old.
 
Hi Jen, you are 25 years old.
</source>
+
</source><br>Note that running '''Sample run 3''' (shown below) will result in an error message. This error happens if you run the script without any arguments. It is important to note that an error such as this can occur, so you can avoid this type of error when creating Python scripts (explained in the next section).  Let's continue in this section for now...
:::2. This final sample run will give us a error. This is important to see this, as we will fix it in the next section. This error happens if you run the script without any arguments. Since we still try to use them. Lets move forward and leave this error, until we have the right tools to fix it.
+
:::'''Sample run 3:'''<source>
:::Sample run 3:<source>
+
./lab2c.py
run lab2c.py
 
 
---------------------------------------------------------------------------
 
---------------------------------------------------------------------------
 
IndexError                                Traceback (most recent call last)
 
IndexError                                Traceback (most recent call last)
Line 161: Line 160:
 
IndexError: list index out of range
 
IndexError: list index out of range
 
</source>
 
</source>
:::3. Download the check script and check your work. Enter the following commands from the bash shell.<source>
+
:::3. Download the checking script and check your work. Enter the following commands from the '''bash shell'''.<source lang="bash">
 
cd ~/ops435/lab2/
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
+
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2c
 
python3 ./CheckLab2.py -f -v lab2c
 
</source>
 
</source>
:::4. Before proceeding, make certain that you identify any and all errors in "lab2c.py". When the check script tells you everything is "ok", you may procede to the next step.
+
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2c.py'''. When the check script tells you everything is '''OK''', you may procede to the next step.
 +
<br><br>
  
= INVESTIGATION 2: IF STATEMENTS =
+
= INVESTIGATION 2: USING CONDITIONAL STATEMENTS =
In computer programming an "if statement" is a condition that executes different code based on whether the condition is True or False. In this section "if statements" will be used to change the way each script runs, based entirely on the output we provide.
+
:In computer programming, control flow statement can be used to change the direction (flow) of a program. The [https://en.wikipedia.org/wiki/Flowchart diagram here] may help you visualize it. In this section, you will focus on LOGIC control flow statements that are used to change the way each script runs, based entirely on input data (either via the input() function, or command arguments via the list object sys.argv). In this section, we will discuss several LOGIC control flow statements including: IF, and IF/ELIF/ELSE.
  
== PART 1 - Indentation and IF Logic==
+
== PART 1 - Using IF Statements ==
Indentation means to start a line with spaces or tabs before your text. In Python, indentation can control how the program itself runs. From now on be very careful and consistent in the indetation that you make. Using indentation you can choose what code runs as part of the if statement and what code runs as part of the main program.
+
 
 +
:An '''IF''' statement is a control flow statement that executes or does not execute different code based on whether the condition is '''True''' or '''False'''.  
  
 
'''Understanding If Statements '''
 
'''Understanding If Statements '''
Line 179: Line 180:
 
:'''Perform the following steps'''
 
:'''Perform the following steps'''
  
:#Open ipython3<source>
+
:#Create a temporary python file for testing things in this section.
ipython3
+
:#Let's create an if statement.<br>Try the following 2 lines, indenting the second line:<source lang="python">
</source>
 
:#Make some if statements and see what happens.<source>
 
 
if True:
 
if True:
 
     print('This print is apart of the if statement')
 
     print('This print is apart of the if statement')
</source>
+
</source>What happened when you ran this code? It is important to note a couple of things with the IF statement:<ul><li>When the expression in an IF statement '''evaluates to True''', it runs the code that is indented underneath it. In this case, we can use the boolean value "True" to make this happen, or test to see if a expression determined true or false.</li><li>However, if the If expression evaluates to '''False''', then it will not run the code indented underneath it. Any code not indented under the if statement will perform normally as the main program and is NOT associated with control flow statement.</li><li>Indentation means to start a line with spaces or tabs before your text. Using '''indentation''' will direct the script what code will run as part of the IF statement and which code will run regardless. Also, using indentation makes it easier for a programmer to identify Control Flow statements. From this point on, be VERY careful and consistent with indentation because it will affect how your code works. </li></ul>
:#When a if statement is True, it runs the code that is indented underneith it. However if the statement is False it will not run. Any code not indented under the if statement will perform normally.<source>
+
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|4 spaces|While python allows some flexibility with your indentation - please don't be creative with it. Always use 4 spaces for each new block. There will be exceptions later on, but start with this now. You may find it helpful to configure your editor to insert for spaces instead of a tab when you press the tab key.}}</blockquote>
 +
<ol><li value='3'>Try the following 3 lines, indenting the second and third lines, but NOT the fourth line:<source lang="python">
 
if False:
 
if False:
 
     print('This first print statement will never run')
 
     print('This first print statement will never run')
 
     print('This second print statement will also not run')
 
     print('This second print statement will also not run')
 
print('This print statement will run')
 
print('This print statement will run')
</source>
+
</source>What do you notice?<br><br>So far, you have been using only the '''Boolean values True or False''' for your IF statements. Although this can be useful, it can be more practical to state an expression that will be evaluated to a '''True''' or '''False''' Boolean value to be used with control flow statements (referred to as: '''Boolean Logic''').<br><br></li>
:#These if statements are using boolean logic, this means they are either True or False. The above code uses if statement that are ALWAYS set, next lets makes a if statement that runs under specific conditions.<source>
+
<li>let's create an IF statement that runs under specific conditions. Issue the following code below:<source lang="python">
 
password = input('Please enter a secret password')
 
password = input('Please enter a secret password')
 
if password == 'P@ssw0rd':
 
if password == 'P@ssw0rd':
 
     print('You have succesfully used the right password')
 
     print('You have succesfully used the right password')
</source>
+
</source>What happened? In the above example, you are making a comparison between the value you entered via the '''input()''' function, which in turn, was saved into the '''password''' object. The IF statement is using that object (named password), followed by '''==''' which represents '''identical to''', followed by the string ''' 'P@ssw0rd' '''. Never use '''=''' to 'compare values since this is used to store the value into an object and may not allow IF statement to properly evaluate the expression!  Also note that a '''space is used to separate arguments with the IF statement'''. The IF statement tests that expression to see if it is '''True or False'''. If that expression is '''True''', it will run the code indented below. On the other hand, if that expression is '''False''', it will not run the code. Try experimenting with different combinations of passwords.<br><br>If statements can also be used to compare numbers. We can do this by using comparison operators (such as: '''==''', '''!=''', '''>''', '''>=''', '''<''', '''<='''), but we can also use functions. The function '''len()''' can be used to return the number of characters in a word (plus other features). length of words and other objects. We can also use the '''len()''' function to give us the number of argumuents provided to our script by using 'len(sys.argv)' and it should return a number. Below we are also using '!='. Which stands for not eqal to. <br><br></li>
:#In the above example we are making a comparison between the value we enter int the input() function, which will be saved into the password variable, and with the word 'P@ssw0rd'. The '==' stands for is equal to, we are asking if the password variable is equal to the word 'P@ssw0rd'. If this condition is True, it will run the code indented below, if the condition is False, it will not run the code. Try experimenting with different combinations of passwords.
+
<li>Try the following program:<source lang="python">
:#If statements can also be used to compare numbers, and use functions. The function 'len()' can be used to give us the length of words and other variables. We can use this 'len()' function to give us the number of arguments provided to our script by using 'len(sys.argv)' and it should return a number. Below we are also using '!='. Which stands for not equal to. <source>
 
 
import sys
 
import sys
  
Line 207: Line 206:
 
     sys.exit()
 
     sys.exit()
  
</source>
+
</source>What happened?</li>
:#This if statement means: IF the number of arguments(one) is NOT EQUAL to ten, then the condition is True. These can get a little confusing, try experimenting and move on when ready.
+
</ol>
:#If you are running this in ipython3, the number of arguments will be always be '1'. This number will always be one higher than the actual number of arguments entered. This is because it also counts the script name as a argument.
+
 
 +
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Number of Arguments with len(sys.argv)|If you are calling the '''len()''' function with the '''sys.argv''' argument, the number of arguments returned will be always be at least '1'. This number will always be one higher than the actual number of arguments entered, since it also counts the script name as a argument.}}</blockquote>
 +
 
 +
''' Practice Using IF Statements'''
 +
:Now it's time to create a new script. You will be modifying the previous Python script to provide a message if the user did NOT provide any argument when running the script, and abort the script if two additional arguments are not provided. Refer to Sample Runs displayed below for exact prompt and output requirements.
 +
 
 +
:'''Perform the following Instructions:'''
 +
 
 +
:#Make a copy of '''lab2c.py''' and call it '''lab2d.py'''.
 +
:#Modify '''lab2d.py''' by adding an if statement immediately BEFORE your print statements. This if statement should make sure that lab2d.py is using '2' additional arguments.
  
''' Practice Using If Statements '''
+
:::'''Input / Output / Processing Requirements'''
:#Now it's time to create a new script. Make a copy of '''lab2c.py''' and call it '''lab2d.py'''. Now modify '''lab2d.py''', add a if statement right before your print statements. This if statement should make sure that lab2d.py is using '2' additional arguments.
 
  
::*The script should have a Shebang line
+
:::*The script should have a '''Shebang line'''
::*The script should import sys
+
:::*The script should '''import sys'''
::*The script should print a usage message IF additional arguments are not given
+
:::*The script should print a '''usage message''' if zero arguments present, or if not exactly 2 arguments are provided when running the script<br>(NOTE: Use '''sys.argv[0]''' value in this message in case you rename the script at a later date!)
::*The script should exit IF two additional arguments are not given
+
:::*The script should exit without attempting to do any more work if exactly 2 arguments are not provided when running script
::*The script should use a variable called "name"
+
:::*The script should use an object called '''name'''
::*The script should use a variable called "age"
+
:::*The script should use an object called '''age'''
::*The script should use sys.argv[1] (first argument)
+
:::*The script should use '''sys.argv[1]''' (first argument)
::*The script should use sys.argv[2] (second argument)
+
:::*The script should use '''sys.argv[2]''' (second argument)
::*The script should store the values in the correct variables
+
:::*The script should store the values in the correct objects
::*The script should print the EXACT OUTPUT as shown
+
:::*The script should print the EXACT OUTPUT as shown
  
:::Sample run 1:<source>
+
:::'''Sample run 1:'''<source>
run lab2d.py Jon 20
+
./lab2d.py Jon 20
 
Hi Jon, you are 20 years old.
 
Hi Jon, you are 20 years old.
 
</source>
 
</source>
:::Sample run 2:<source>
+
:::'''Sample run 2:'''<source>
run lab2d.py Jen 25
+
./lab2d.py Jen 25
 
Hi Jen, you are 25 years old.
 
Hi Jen, you are 25 years old.
 
</source>
 
</source>
:::Sample run 3:<source>
+
:::'''Sample run 3:'''<source>
run lab2d.py  
+
./lab2d.py  
Usage: lab2d.py [name] [age]
+
Usage: ./lab2d.py name age
 
</source>
 
</source>
:::Sample run 4:<source>
+
:::'''Sample run 4:'''<source>
run lab2d.py Jon is 20
+
./lab2d.py Jon is 20
Usage: lab2d.py [name] [age]
+
Usage: ./lab2d.py name age
 
</source>
 
</source>
:::2. Download the check script and check your work. Enter the following commands from the bash shell.<source>
+
:::3. Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
 
cd ~/ops435/lab2/
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
+
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2d
 
python3 ./CheckLab2.py -f -v lab2d
 
</source>
 
</source>
  
:::3. Before proceeding, make certain that you identify any and all errors in "lab2d.py". When the check script tells you everything is "ok", you may procede to the next step.
+
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2d.py'''. When the check script tells you everything is '''OK''', you may procede to the next step.
  
== PART 2 - IF/ELSE/ELIF ==
+
== PART 2 - Using IF/ELIF/ELSE Statements ==
There are many ways to use if statements in more advanced configurations. This section will give a few examples and explain them.  
+
:There are many ways to use IF statements in more advanced configurations. This section will provide a few more examples and provide an explanation of how they work.  
  
:'''Perform the following steps'''
+
#For the following examples, try changing the numbers in the objects to get different results.
 
+
#Create one or more new files for testing the following steps (you won't need to submit them).
:#For the following examples, try changing the numbers in the variables to get different results.
+
#Let's use an IF statement testing a condition of two object values. In this case, if object 'a' is greater than object 'b', then print a message, if False, do nothing.<source lang="python">
:#Open ipython3<source>
 
ipython3
 
</source>
 
:#Using if statements to do numeric comparisons, if variable 'a' is greater than variable 'b', this if statements condition will be True:<source>
 
 
a = 10
 
a = 10
 
b = 15
 
b = 15
 
if a > b:
 
if a > b:
 
     print('a is greater than b')
 
     print('a is greater than b')
</source>
+
</source>What happened? Let's now use an IF/ELSE statement.<br><br>
:#But we may want to know if 'a' is less than 'b'. The 'elif' statement allows us to string together multiple if statement. This new statement 'elif' means: IF the first condition is False, it will check the second condition under 'elif'. HOWEVER, if the first condition is True, it will run the code indented under the first condition and SKIP the 'elif' statement.<source>
+
#Try the following code instead:<source lang="python">
 
a = 10
 
a = 10
 
b = 15
 
b = 15
 
if a > b:
 
if a > b:
 
     print('a is greater than b')
 
     print('a is greater than b')
elif a < b:
+
else:
 
     print('b is greater than a')
 
     print('b is greater than a')
</source>
+
</source>What happened?<br><br>This is neat, but what if 'a' is equal to 'b'? In order to make this work, we would need to perform another test! The 'elif' statement allows us to string together multiple if statement. This new statement 'elif' means: IF the first expression is False, it will check the second expression under 'elif'. HOWEVER, if the first expression is True, it will run the code indented under the first expression and SKIP the 'elif' statement. Finally, we include the ELSE statement - in this case, if 'a' is equal to 'b' (i.e. fails first test since 'a' is not greater than 'b' and fails second test since 'a' is not less than 'b', so they must be equal to check other).<br><br>
:#In the event that we want to know if 'a' and 'b' are equal to each other, we could add another 'elif' using the '==' equal signs, but instead lets use 'else'. The 'else' statement will run the code indented under it only when all the 'if' and 'elif' statements above are False. <source>  
+
#Modify your program to looks like this:<source lang="python">a = 10
a = 10
+
b = 10
b = 15
 
 
if a > b:
 
if a > b:
 
     print('a is greater than b')
 
     print('a is greater than b')
Line 283: Line 285:
 
     print('a is not greater than b')
 
     print('a is not greater than b')
 
     print('a is not less than b')
 
     print('a is not less than b')
 +
    print('Therefore, a is equal to b')
 
</source>
 
</source>
  
= INVESTIGATION 3: LOOPS =
+
= INVESTIGATION 3: USING LOOP STATEMENTS =
In programming loops are sequences of code that are repeated multiple times or until a condition is satisfied.
+
:In the first two labs, you have been exposed to tools and methods to write powerful Python scripts. In Lab1, this included using using variables. In Lab 2 you learned how to input variables by either prompting the user for input or using data that are arguments containing within a Python script that you run. You also learned about LOGIC control-flow statements in order to make the Python script behave differently based on differing input.
  
== PART 1 - WHILE Loops ==
+
:You will start to learn about the second major category of control flow statements by learning how to repeat a command or a series of commands. Although, you will be learning other scripting techniques, the ability to know how to use variables, CONDITIONAL and LOOPING control-flow statements will allow you to create useful and powerful programs to assist you when managing your computer system (including virtual machines).
While loops use a the same type of conditions found in if statements. While the condition is True, the code indented under the while loop will be repeated. When the condition becomes False the loop will stop repeating.
+
 
 +
== PART 1 - Understanding WHILE Loops ==
 +
:'''WHILE loops''' use a the same type of conditions found in if statements. While the condition is True, the code indented under the while loop will be repeated. When the condition becomes False the loop will stop repeating.
  
''' Understanding While Loops '''
 
 
:'''Perform the following steps'''
 
:'''Perform the following steps'''
:#Open ipython3<source>
+
:#Create a temporary python file for practicing with the followin examples.
ipython3
+
:#A '''WHILE''' loop is not the most common type of loop in Python but it's the simplest. Below is a WHILE loop which will run five times. Each time the loop is run, it will add one to the count variable, increasing the variables number:<source lang="python">
</source>
 
:#Below is a program that will count to 5. Each time the loop is run, it will add one to the count variable, increasing the variables number.<source>
 
 
count = 0
 
count = 0
 
while count != 5:
 
while count != 5:
Line 302: Line 304:
 
     count = count + 1
 
     count = count + 1
 
print('loop has ended')
 
print('loop has ended')
</source>
+
</source>Sometimes you know in advance how many times a loop will execute but often you don't. For example loops are extremely useful for '''error-checking''' in order to prevent incorrect data being accepted and causing the script not to perform correctly.<br>
:#Here is an example of guessing the correct password:<source>
+
:#Here is an example of a loop used for error-checking. Run this code and type several incorrect passwords then the correct one to see what happens:<source lang="python">
 
password = ''
 
password = ''
 
while password != 'P@ssw0rd':
 
while password != 'P@ssw0rd':
Line 310: Line 312:
 
</source>
 
</source>
  
 +
:Now it's time to create a new script. You will be creating an entirely new Python script to use a WHILE loop as a determinant loop. This while loop will count down from 10, print each value as it counts down. When it gets to the end it will output 'blast off!' Refer to Sample Runs displayed below for exact prompt and output requirements.
  
'''Practice Using a While Loop'''
+
:'''Perform the following Instructions:'''
:#Now it's time to create a new script. Make a new file called '''lab2e.py''', this script will contain a while loop. This while loop will count down from 10, print each value as it counts down. When it gets to the end it will output 'blast off!'.
 
  
::*The script should have a Shebang line
+
:#Make a new file called '''lab2e.py''', this script will contain a WHILE loop.
::*The script should use a variable named timer with a value of 10
+
 
::*The script should have a while loop that repeats until timer equals 0
+
:::'''Input / Output / Processing Requirements'''
::*The script should print the EXACT OUTPUT as shown
+
 
:::Sample run:<source>
+
:::*The script should have a Shebang line
run lab2e.py
+
:::*The script should use a variable named timer with a value of 10
 +
:::*The script should have a while loop that repeats until timer equals 0
 +
:::*The script should print the EXACT OUTPUT as shown
 +
 
 +
:::'''Sample run:'''<source>
 +
./lab2e.py
 
10
 
10
 
9
 
9
Line 332: Line 339:
 
blast off!
 
blast off!
 
</source>
 
</source>
 
+
:::2. Download the check script and check your work. Enter the following commands from the bash shell.<source lang="bash">
:::2. Download the check script and check your work. Enter the following commands from the bash shell.<source>
 
 
cd ~/ops435/lab2/
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
+
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2e
 
python3 ./CheckLab2.py -f -v lab2e
 
</source>
 
</source>
:::3. Before proceeding, make certain that you identify any and all errors in "lab2d.py". When the check script tells you everything is "ok", you may procede to the next step.
+
:::3. Before proceeding, make certain that you identify any and all errors in '''lab2e.py'''. When the check script tells you everything is '''OK''', you may proceed to the next step.
  
== PART 2 - WHILE Loops with Arguments ==
+
== PART 2 - Using WHILE loops with script arguments ==
  
''' Understand While Loops and Arguments '''
+
:You will now learn to make your Python scripts more flexible by using numbers as arguments to be used with WHILE loops. You will learn that arguments used in Python scripts are strings (not numbers) and therefore, cannot be used in Mathematical operations unless they are converted into numbers (like an integer). You will be learning how to use the int() function in order to convert a string into an integer.
:#Now lets make the same script more intelligent. Make a copy of '''lab2e.py''' and call it '''lab2f.py'''. Now modify '''lab2f.py''', modify the value of timer to user the first argument provided to the script. This will allow the argument to choose how long the timer is.
+
 
:::'''WARNING: When using arguments as numbers/integers or performing math on arguments you must wrap them in the int() function, for example: number = int(sys.argv[1])'''
+
:'''Perform the Following Steps:'''
::*The script should have a Shebang line
+
 
::*The script should import sys
+
:#Make a copy of '''lab2e.py''' and call it '''lab2f.py'''.
::*The script should use a variable named timer with the value of int(sys.argv[1])  
+
:#Modify '''lab2f.py''' to change the initial value of the variable '''count''' to the first argument when running your Python script. '''WARNING:''' When using arguments as numbers/integers or performing math on arguments you must wrap them in the int() function, for example: '''count = int(sys.argv[1])'''
::*The script should have a while loop that repeats until timer equals 0
+
 
::*The script should print the EXACT OUTPUT as shown
+
:::'''Additional Input / Output / Processing Requirements'''
:::Sample run 1:<source>
+
 
run lab2f.py 10
+
:::*The script should have a '''Shebang line'''
 +
:::*The script should '''import sys'''
 +
:::*The script should use a variable named timer with the value of '''int(sys.argv[1])'''
 +
:::*The script should have a while loop that repeats until timer equals 0
 +
:::*The script should print the EXACT OUTPUT as shown
 +
 
 +
:::'''Sample run 1:'''<source>
 +
./lab2f.py 10
 
10
 
10
 
9
 
9
Line 365: Line 378:
 
blast off!
 
blast off!
 
</source>
 
</source>
:::Sample run 2:<source>
+
:::'''Sample run 2:'''<source>
run lab2f.py 3
+
./lab2f.py 3
 
3
 
3
 
2
 
2
Line 372: Line 385:
 
blast off!
 
blast off!
 
</source>
 
</source>
:::2. Download the check script and check your work. Enter the following commands from the bash shell.<source>
+
:::3. Download the check script and check your work. Enter the following commands from the bash shell.<source lang="bash">
 
cd ~/ops435/lab2/
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
+
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2f
 
python3 ./CheckLab2.py -f -v lab2f
 
</source>
 
</source>
:::3. Before proceeding, make certain that you identify any and all errors in "lab2d.py". When the check script tells you everything is "ok", you may procede to the next step.
+
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2d.py'''. When the check script tells you everything is '''OK''', you may proceed to the next step.
  
== PART 3 - WHILE Loops With IF Statement==
+
== PART 3 - Combining WHILE loops with IF statements==
  
''' Practice Using Loops With IF Statements '''
+
:Let's improve upon your previous shell script to further prevent errors from incorrect input. You can combine LOGIC control-flow statements with other LOGIC control-flow statements for more complex programming. For example, if you ran the previous Python script without an argument (i.e. empty string), you would encounter an error since it could not convert an empty string to an integer.
:#Now lets make the same script EVEN more intelligent. Make a copy of '''lab2f.py''' and call it '''lab2g.py'''. Now modify '''lab2g.py''', add a if statement to the script that checks to see if a argument was entered. If a argument was entered use that number for the timer, if no argument was entered, timer should equal 3.  
 
  
:::'''WARNING: When using arguments as numbers/integers or performing math on arguments you must wrap them in the int() function: number = int(sys.argv[1])'''
+
:''' Perform the Following Steps '''
:::'''WARNING: Remember to check the number of arguments using len(sys.argv) in a if statement'''
 
  
::*The script should have a Shebang line
+
:#Make a copy of '''lab2f.py''' and call it '''lab2g.py'''.
::*The script should import sys
+
:#Modify '''lab2g.py''', add an IF statement to the script that checks to see if a argument was entered. If a argument was entered use that number for the timer, if no argument was entered, then by default, the timer should equal 3.
::*The script should use a variable named timer with the value of 3 if no arguments are entered  
 
::*The script should use a variable named timer with the value of int(sys.argv[1]) if arguments are entered
 
::*The script should have a while loop that repeats until timer equals 0
 
::*The script should print the EXACT OUTPUT as shown
 
  
:::Sample run 1:<source>
+
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|ADDITIONAL WARNINGS|When using arguments as numbers/integers or performing math on arguments you must wrap them in the '''int()''' function:<br><source>timer = int(sys.argv[1])</source>Remember to check the number of arguments in an IF statement using:<source>len(sys.argv)</source>}}</blockquote>
run lab2g.py 5
+
 
 +
:::'''Additional Input / Output / Processing Requirements'''
 +
 
 +
:::*The script should have a '''Shebang line'''
 +
:::*The script should '''import sys'''
 +
:::*The script should use a variable named '''timer''' with the value of '''3''' if '''no arguments''' are entered
 +
:::*The script should use a variable named timer with the value of '''int(sys.argv[1])''' if '''arguments''' are entered
 +
:::*The script should have a WHILE loop that repeats until (and not including when) timer equals 0
 +
:::*The script should print the EXACT OUTPUT as shown
 +
 
 +
:::'''Sample run 1:'''<source>
 +
./lab2g.py 5
 
5
 
5
 
4
 
4
Line 405: Line 423:
 
</source>
 
</source>
  
:::Sample run 2:<source>
+
:::'''Sample run 2:'''<source>
run lab2g.py 2
+
./lab2g.py 2
 
2
 
2
 
1
 
1
Line 412: Line 430:
 
</source>
 
</source>
  
:::Sample run 3:<source>
+
:::'''Sample run 3:'''<source>
run lab2g.py
+
./lab2g.py
 
3
 
3
 
2
 
2
Line 419: Line 437:
 
blast off!
 
blast off!
 
</source>
 
</source>
:::2. Download the check script and check your work. Enter the following commands from the bash shell.<source>
+
:::3. Download the check script and check your work. Enter the following commands from the bash shell.<source lang="bash">
 
cd ~/ops435/lab2/
 
cd ~/ops435/lab2/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py
+
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
 
python3 ./CheckLab2.py -f -v lab2g
 
python3 ./CheckLab2.py -f -v lab2g
 
</source>
 
</source>
  
:::3. Before proceeding, make certain that you identify any and all errors in "lab2d.py". When the check script tells you everything is "ok", you may procede to the next step.
+
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2f.py'''. When the check script tells you everything is '''OK''', you may proceed to the next step.
 +
<br><br>
  
 
= LAB 2 SIGN-OFF (SHOW INSTRUCTOR) =
 
= LAB 2 SIGN-OFF (SHOW INSTRUCTOR) =
Line 436: Line 455:
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>./CheckLab2.py -f -v</code>
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>./CheckLab2.py -f -v</code>
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>cat lab2a.py lab2b.py lab2c.py lab2d.py lab2e.py lab2f.py lab2g.py</code>
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>cat lab2a.py lab2b.py lab2c.py lab2d.py lab2e.py lab2f.py lab2g.py</code>
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Lab2 logbook notes completed
 
<br><br>
 
  
 +
:'''Be able to answer any questions about the lab to show that you understood it!'''
 +
 +
= LAB REVIEW =
  
= Practice For Quizzes, Tests, Midterm &amp; Final Exam =
+
:# Write a short Python script to ask the user to provide their shoe size at the keyboard, and store the result in an integer object called '''shoeSize'''.
 +
:# Add codes to the previous Python script to display the shoe size entered using the same integer object created. (For example: '''Your size size is: 16''').
 +
:# What is the purpose of importing special module from your system?
 +
:# Write a short Python script to display two arguments from running your Python script.<br>For example if your Python script was called '''myscript.py''' and you issued the command:<br>'''python myscript.py happy afternoon''', you would get the following output:<br><br>The first argument is: happy<br>The second argument is afternoon<br><br>
 +
:# What is the purpose of using an '''if''' statement?
 +
:# What is the purpose of using an '''if-else''' statement?
 +
:# Write a short Python script which terminates the execution of the Python script if there are not exactly 3 arguments given at the command line.
 +
:# What is the purpose of an '''if-elif-else''' statement?
 +
:# Write a Python script to prompt the user for a course mark (no error checking is required... you can assume that the input will be a valid mark from 0 to 100). Use an if-elif-else statement to convert the mark to a letter grade. For simplicity, you don't have to worry about D+, C+, B+, or A+
 +
:# Write a Python script to print the text '''I love Python''' twenty times (on a separate line).
 +
:# Identify and list the Python 3 keywords used in this lab.
 +
:# Identify and list the Python 3 built-in functions used in this lab. (hint: the functions provided by the __builtins__ module)
 +
:# '''INTERESTING CHALLENGE:''' Perform a Netsearch to see how you can write Python code to perform error-checking (using a loop) to force a user to enter a number for the shoe size script (created in question #2). There are two things to consider:<ol type="a"><li>A number as opposed to a string</li><li>It has to be an acceptable range from 1 to 20</li></ol>
  
:# x
+
[[Category:OPS435-Python]]
:# x
 
:# x
 

Latest revision as of 08:25, 21 January 2020

** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **

LAB OBJECTIVES

This lab will cover the necessary methods to allow a user to interact with a running Python script.
Objectives
Write Python code in order to:
  • Accept data from users that run a Python script, such as a username or password.
  • Process the inputted data using Conditional Statements.
This means that the program will change how it behaves based on the input given, an example would be, providing the correct password or providing the wrong password.
  • Process the inputted data using Looping Statements.
Looping (iteration) is the ability for your program to repeatedly run the same block of codes over and over. An example of this, could be found when you provide the incorrect password to a login page and it responds with, 3 attempts to login remaining.



INVESTIGATION 1: USER INPUT

PART 1 - User Input

In this section, you will learn how to prompt (ask) the user running the python script for input or data. Although you will not be immediately be using the data that the user provided, you will use that data later in this lab to change how a Python script works in different situations.

Storing User Input data to Python objects

Perform the following steps:
  1. Launch your Centos VM, open your code editor, and a a shell terminal (as a regular user) for executing your code.
  2. To begin, let's start out with a very basic script. This script will use objects that will display specific values to your terminal. Create the file lab2a.py in your ~/ops435/lab2 directory, containing the following content:
    #!/usr/bin/env python3
    
    name = 'Jon'
    age = 20
    print('Hi ' + name + ', you are ' + str(age) + ' years old.')
  3. Try running this script and study the output:
    ./lab2a.py
    This Python script is not very useful: it displays the same output regardless of the number of times that the Python script is run.
    The input() function is used to obtain information from the user and store it into an object (also called a variable). It is typical to place a question (or hint) as a argument in the input() function: this will aid the user in typing in the correct data.

  4. Replace the print() call in your lab2a.py with the following (you can just comment-out the print() call using a # at the beginning of the line):
    colour = input("Type in a colour and press enter: ")
  5. When prompted, type the text: red and press ENTER. Did anything display? Why not?
  6. Add another line to your script:
    print(colour)
    What was displayed?
  7. Now replace that line with this:
    print('The colour I typed in is: ' + colour)
    Note what was displayed.

Practice Storing User Input data

Now it's time to create a new script to prompt the user to enter data and display that data on their terminal. Refer to object name and prompt text information when creating your Python script. Refer to Sample Runs displayed below for exact prompt and output requirements.
Perform the following Instructions:
  1. Make a copy of lab2a.py and call it lab2b.py.
  2. Modify lab2b.py so that it prompts the user for both the user's name and age.
Input / Output Requirements
  • The script should have a Shebang line
  • The script should use an object called name
  • The script should use an object called age
  • The script should prompt the user for "Name: "
  • The script should prompt the user for "Age: "
  • The script should store the values in the correctly spelled objects (case sensitivity counts)
  • The script should print the EXACT OUTPUT as shown (case sensitivity counts)
Sample run 1:
./lab2b.py
Name: Jon
Age: 20
Hi Jon, you are 20 years old.
Sample run 2:
./lab2b.py
Name: Jen
Age: 25
Hi Jen, you are 25 years old.
3. Download the checking script and check your work. Run the following commands from the bash shell.
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2b
4. Before proceeding, make certain that you identify any and all errors in lab2b.py. When the check script tells you everything is OK, you may procede to the next step.

PART 2 - Arguments

An argument is a 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:

  1. Use a temporary file for testing your work for this section.
  2. 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.

  3. Start with the following line to import additional python objects:
    import sys
  4. Call the following functions and note what they do:
    print(sys.version) # tells us the version of the python currently 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

    Instead of using the input() function to prompt the user for data, we can use the sys.argv list object to store data as a result of running the Python script with arguments. The list object sys.argv, when used within your Python script can store the following:
    • sys.argv - stores all argument items
    • sys.argv[0] - stores the name of the script/program
    • sys.argv[1] - stores the first argument
    • sys.argv[2] - stores the second argument
    • etc...
    • len(sys.argv) - gives the number of arguments

  5. Create a new script called ~/ops435/lab2/showargs.py and add the following content:
    #!/usr/bin/env python3
    
    import sys
    
    arguments = sys.argv
    name = sys.argv[0]
    
    print('Print out ALL script arguments: ', arguments)
    print('Print out the script name: ' + name)
    print('Print out the number of argument: ', len(sys.argv))
  6. Run the script and examine the output by running the Python script without and with arguments:
    ./showargs.py
    ./showargs.py testing different arguments
    ./showargs.py argument1 argument2 argument3 argument4

Practice Using Arguments

Now it's time to create a new script, but unlike prompting the user for data, the data (as arguments from running your Python script) will be used instead. Refer to variable name and prompt text information when creating your Python script. Refer to Sample Runs displayed below for exact prompt and output requirements.
Perform the following Instructions:
  1. Make a copy of lab2b.py and call it lab2c.py.
  2. Modify lab2c.py to use the sys.argv[1] and sys.argv[2] functions instead of the input() function (used in your previous lab2b.py script).
Input / Output Requirements
  • The script should have a Shebang line
  • The script should contain import sys
  • The script should use a variable called name
  • The script should use a variable called age
  • The script should use sys.argv[1] (first argument)
  • The script should use sys.argv[2] (second argument)
  • The script should store the values in the correct variables (including case sensitivity)
  • The script should print the EXACT OUTPUT as shown (including case sensitivity)
Sample run 1:
./lab2c.py Jon 20
Hi Jon, you are 20 years old.
Sample run 2:
./lab2c.py Jen 25
Hi Jen, you are 25 years old.

Note that running Sample run 3 (shown below) will result in an error message. This error happens if you run the script without any arguments. It is important to note that an error such as this can occur, so you can avoid this type of error when creating Python scripts (explained in the next section). Let's continue in this section for now...
Sample run 3:
./lab2c.py
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

...
...
...

IndexError: list index out of range
3. Download the checking script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2c
4. Before proceeding, make certain that you identify any and all errors in lab2c.py. When the check script tells you everything is OK, you may procede to the next step.



INVESTIGATION 2: USING CONDITIONAL STATEMENTS

In computer programming, control flow statement can be used to change the direction (flow) of a program. The diagram here may help you visualize it. In this section, you will focus on LOGIC control flow statements that are used to change the way each script runs, based entirely on input data (either via the input() function, or command arguments via the list object sys.argv). In this section, we will discuss several LOGIC control flow statements including: IF, and IF/ELIF/ELSE.

PART 1 - Using IF Statements

An IF statement is a control flow statement that executes or does not execute different code based on whether the condition is True or False.

Understanding If Statements

Perform the following steps
  1. Create a temporary python file for testing things in this section.
  2. Let's create an if statement.
    Try the following 2 lines, indenting the second line:
    if True:
        print('This print is apart of the if statement')
    What happened when you ran this code? It is important to note a couple of things with the IF statement:
    • When the expression in an IF statement evaluates to True, it runs the code that is indented underneath it. In this case, we can use the boolean value "True" to make this happen, or test to see if a expression determined true or false.
    • However, if the If expression evaluates to False, then it will not run the code indented underneath it. Any code not indented under the if statement will perform normally as the main program and is NOT associated with control flow statement.
    • Indentation means to start a line with spaces or tabs before your text. Using indentation will direct the script what code will run as part of the IF statement and which code will run regardless. Also, using indentation makes it easier for a programmer to identify Control Flow statements. From this point on, be VERY careful and consistent with indentation because it will affect how your code works.
Important.png
4 spaces
While python allows some flexibility with your indentation - please don't be creative with it. Always use 4 spaces for each new block. There will be exceptions later on, but start with this now. You may find it helpful to configure your editor to insert for spaces instead of a tab when you press the tab key.
  1. Try the following 3 lines, indenting the second and third lines, but NOT the fourth line:
    if False:
        print('This first print statement will never run')
        print('This second print statement will also not run')
    print('This print statement will run')
    What do you notice?

    So far, you have been using only the Boolean values True or False for your IF statements. Although this can be useful, it can be more practical to state an expression that will be evaluated to a True or False Boolean value to be used with control flow statements (referred to as: Boolean Logic).

  2. let's create an IF statement that runs under specific conditions. Issue the following code below:
    password = input('Please enter a secret password')
    if password == 'P@ssw0rd':
        print('You have succesfully used the right password')
    What happened? In the above example, you are making a comparison between the value you entered via the input() function, which in turn, was saved into the password object. The IF statement is using that object (named password), followed by == which represents identical to, followed by the string 'P@ssw0rd' . Never use = to 'compare values since this is used to store the value into an object and may not allow IF statement to properly evaluate the expression! Also note that a space is used to separate arguments with the IF statement. The IF statement tests that expression to see if it is True or False. If that expression is True, it will run the code indented below. On the other hand, if that expression is False, it will not run the code. Try experimenting with different combinations of passwords.

    If statements can also be used to compare numbers. We can do this by using comparison operators (such as: ==, !=, >, >=, <, <=), but we can also use functions. The function len() can be used to return the number of characters in a word (plus other features). length of words and other objects. We can also use the len() function to give us the number of argumuents provided to our script by using 'len(sys.argv)' and it should return a number. Below we are also using '!='. Which stands for not eqal to.

  3. Try the following program:
    import sys
    
    print(len(sys.argv))
    
    if len(sys.argv) != 10:
        print('you do not have 10 arguments')
        sys.exit()
    What happened?
Important.png
Number of Arguments with len(sys.argv)
If you are calling the len() function with the sys.argv argument, the number of arguments returned will be always be at least '1'. This number will always be one higher than the actual number of arguments entered, since it also counts the script name as a argument.

Practice Using IF Statements

Now it's time to create a new script. You will be modifying the previous Python script to provide a message if the user did NOT provide any argument when running the script, and abort the script if two additional arguments are not provided. Refer to Sample Runs displayed below for exact prompt and output requirements.
Perform the following Instructions:
  1. Make a copy of lab2c.py and call it lab2d.py.
  2. Modify lab2d.py by adding an if statement immediately BEFORE your print statements. This if statement should make sure that lab2d.py is using '2' additional arguments.
Input / Output / Processing Requirements
  • The script should have a Shebang line
  • The script should import sys
  • The script should print a usage message if zero arguments present, or if not exactly 2 arguments are provided when running the script
    (NOTE: Use sys.argv[0] value in this message in case you rename the script at a later date!)
  • The script should exit without attempting to do any more work if exactly 2 arguments are not provided when running script
  • The script should use an object called name
  • The script should use an object called age
  • The script should use sys.argv[1] (first argument)
  • The script should use sys.argv[2] (second argument)
  • The script should store the values in the correct objects
  • The script should print the EXACT OUTPUT as shown
Sample run 1:
./lab2d.py Jon 20
Hi Jon, you are 20 years old.
Sample run 2:
./lab2d.py Jen 25
Hi Jen, you are 25 years old.
Sample run 3:
./lab2d.py 
Usage: ./lab2d.py name age
Sample run 4:
./lab2d.py Jon is 20
Usage: ./lab2d.py name age
3. Download the checking script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2d
4. Before proceeding, make certain that you identify any and all errors in lab2d.py. When the check script tells you everything is OK, you may procede to the next step.

PART 2 - Using IF/ELIF/ELSE Statements

There are many ways to use IF statements in more advanced configurations. This section will provide a few more examples and provide an explanation of how they work.
  1. For the following examples, try changing the numbers in the objects to get different results.
  2. Create one or more new files for testing the following steps (you won't need to submit them).
  3. Let's use an IF statement testing a condition of two object values. In this case, if object 'a' is greater than object 'b', then print a message, if False, do nothing.
    a = 10
    b = 15
    if a > b:
        print('a is greater than b')
    What happened? Let's now use an IF/ELSE statement.

  4. Try the following code instead:
    a = 10
    b = 15
    if a > b:
        print('a is greater than b')
    else:
        print('b is greater than a')
    What happened?

    This is neat, but what if 'a' is equal to 'b'? In order to make this work, we would need to perform another test! The 'elif' statement allows us to string together multiple if statement. This new statement 'elif' means: IF the first expression is False, it will check the second expression under 'elif'. HOWEVER, if the first expression is True, it will run the code indented under the first expression and SKIP the 'elif' statement. Finally, we include the ELSE statement - in this case, if 'a' is equal to 'b' (i.e. fails first test since 'a' is not greater than 'b' and fails second test since 'a' is not less than 'b', so they must be equal to check other).

  5. Modify your program to looks like this:
    a = 10
    b = 10
    if a > b:
        print('a is greater than b')
    elif a < b:
        print('b is greater than a')
    else:
        print('a is not greater than b')
        print('a is not less than b')
        print('Therefore, a is equal to b')

INVESTIGATION 3: USING LOOP STATEMENTS

In the first two labs, you have been exposed to tools and methods to write powerful Python scripts. In Lab1, this included using using variables. In Lab 2 you learned how to input variables by either prompting the user for input or using data that are arguments containing within a Python script that you run. You also learned about LOGIC control-flow statements in order to make the Python script behave differently based on differing input.
You will start to learn about the second major category of control flow statements by learning how to repeat a command or a series of commands. Although, you will be learning other scripting techniques, the ability to know how to use variables, CONDITIONAL and LOOPING control-flow statements will allow you to create useful and powerful programs to assist you when managing your computer system (including virtual machines).

PART 1 - Understanding WHILE Loops

WHILE loops use a the same type of conditions found in if statements. While the condition is True, the code indented under the while loop will be repeated. When the condition becomes False the loop will stop repeating.
Perform the following steps
  1. Create a temporary python file for practicing with the followin examples.
  2. A WHILE loop is not the most common type of loop in Python but it's the simplest. Below is a WHILE loop which will run five times. Each time the loop is run, it will add one to the count variable, increasing the variables number:
    count = 0
    while count != 5:
        print(count)
        count = count + 1
    print('loop has ended')
    Sometimes you know in advance how many times a loop will execute but often you don't. For example loops are extremely useful for error-checking in order to prevent incorrect data being accepted and causing the script not to perform correctly.
  3. Here is an example of a loop used for error-checking. Run this code and type several incorrect passwords then the correct one to see what happens:
    password = ''
    while password != 'P@ssw0rd':
        password = input("Type in a password: ")
    print('Congratulations you guessed the correct password!')
Now it's time to create a new script. You will be creating an entirely new Python script to use a WHILE loop as a determinant loop. This while loop will count down from 10, print each value as it counts down. When it gets to the end it will output 'blast off!' Refer to Sample Runs displayed below for exact prompt and output requirements.
Perform the following Instructions:
  1. Make a new file called lab2e.py, this script will contain a WHILE loop.
Input / Output / Processing Requirements
  • The script should have a Shebang line
  • The script should use a variable named timer with a value of 10
  • The script should have a while loop that repeats until timer equals 0
  • The script should print the EXACT OUTPUT as shown
Sample run:
./lab2e.py
10
9
8
7
6
5
4
3
2
1
blast off!
2. Download the check script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2e
3. Before proceeding, make certain that you identify any and all errors in lab2e.py. When the check script tells you everything is OK, you may proceed to the next step.

PART 2 - Using WHILE loops with script arguments

You will now learn to make your Python scripts more flexible by using numbers as arguments to be used with WHILE loops. You will learn that arguments used in Python scripts are strings (not numbers) and therefore, cannot be used in Mathematical operations unless they are converted into numbers (like an integer). You will be learning how to use the int() function in order to convert a string into an integer.
Perform the Following Steps:
  1. Make a copy of lab2e.py and call it lab2f.py.
  2. Modify lab2f.py to change the initial value of the variable count to the first argument when running your Python script. WARNING: When using arguments as numbers/integers or performing math on arguments you must wrap them in the int() function, for example: count = int(sys.argv[1])
Additional Input / Output / Processing Requirements
  • The script should have a Shebang line
  • The script should import sys
  • The script should use a variable named timer with the value of int(sys.argv[1])
  • The script should have a while loop that repeats until timer equals 0
  • The script should print the EXACT OUTPUT as shown
Sample run 1:
./lab2f.py 10
10
9
8
7
6
5
4
3
2
1
blast off!
Sample run 2:
./lab2f.py 3
3
2
1
blast off!
3. Download the check script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2f
4. Before proceeding, make certain that you identify any and all errors in lab2d.py. When the check script tells you everything is OK, you may proceed to the next step.

PART 3 - Combining WHILE loops with IF statements

Let's improve upon your previous shell script to further prevent errors from incorrect input. You can combine LOGIC control-flow statements with other LOGIC control-flow statements for more complex programming. For example, if you ran the previous Python script without an argument (i.e. empty string), you would encounter an error since it could not convert an empty string to an integer.
Perform the Following Steps
  1. Make a copy of lab2f.py and call it lab2g.py.
  2. Modify lab2g.py, add an IF statement to the script that checks to see if a argument was entered. If a argument was entered use that number for the timer, if no argument was entered, then by default, the timer should equal 3.
Important.png
ADDITIONAL WARNINGS
When using arguments as numbers/integers or performing math on arguments you must wrap them in the int() function:
timer = int(sys.argv[1])
Remember to check the number of arguments in an IF statement using:
len(sys.argv)
Additional Input / Output / Processing Requirements
  • The script should have a Shebang line
  • The script should import sys
  • The script should use a variable named timer with the value of 3 if no arguments are entered
  • The script should use a variable named timer with the value of int(sys.argv[1]) if arguments are entered
  • The script should have a WHILE loop that repeats until (and not including when) timer equals 0
  • The script should print the EXACT OUTPUT as shown
Sample run 1:
./lab2g.py 5
5
4
3
2
1
blast off!
Sample run 2:
./lab2g.py 2
2
1
blast off!
Sample run 3:
./lab2g.py
3
2
1
blast off!
3. Download the check script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2g
4. Before proceeding, make certain that you identify any and all errors in lab2f.py. When the check script tells you everything is OK, you may proceed to the next step.



LAB 2 SIGN-OFF (SHOW INSTRUCTOR)

Students should be prepared with all required commands (system information) displayed in a terminal (or multiple terminals) prior to calling the instructor for signoff.


Have Ready to Show Your Instructor:
Output of: ./CheckLab2.py -f -v
Output of: cat lab2a.py lab2b.py lab2c.py lab2d.py lab2e.py lab2f.py lab2g.py
Be able to answer any questions about the lab to show that you understood it!

LAB REVIEW

  1. Write a short Python script to ask the user to provide their shoe size at the keyboard, and store the result in an integer object called shoeSize.
  2. Add codes to the previous Python script to display the shoe size entered using the same integer object created. (For example: Your size size is: 16).
  3. What is the purpose of importing special module from your system?
  4. Write a short Python script to display two arguments from running your Python script.
    For example if your Python script was called myscript.py and you issued the command:
    python myscript.py happy afternoon, you would get the following output:

    The first argument is: happy
    The second argument is afternoon

  5. What is the purpose of using an if statement?
  6. What is the purpose of using an if-else statement?
  7. Write a short Python script which terminates the execution of the Python script if there are not exactly 3 arguments given at the command line.
  8. What is the purpose of an if-elif-else statement?
  9. Write a Python script to prompt the user for a course mark (no error checking is required... you can assume that the input will be a valid mark from 0 to 100). Use an if-elif-else statement to convert the mark to a letter grade. For simplicity, you don't have to worry about D+, C+, B+, or A+
  10. Write a Python script to print the text I love Python twenty times (on a separate line).
  11. Identify and list the Python 3 keywords used in this lab.
  12. Identify and list the Python 3 built-in functions used in this lab. (hint: the functions provided by the __builtins__ module)
  13. INTERESTING CHALLENGE: Perform a Netsearch to see how you can write Python code to perform error-checking (using a loop) to force a user to enter a number for the shoe size script (created in question #2). There are two things to consider:
    1. A number as opposed to a string
    2. It has to be an acceptable range from 1 to 20