Difference between revisions of "OPS435 Python Lab 2"
(→PART 2 - Understanding WHILE Loops with Arguments) |
(→PART 3 - WHILE Loops With IF Statement) |
||
Line 409: | Line 409: | ||
:::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. | :::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 | + | == PART 3 - Using WHILE Loops With IF Statements== |
''' Practice Using Loops With IF Statements ''' | ''' Practice Using Loops With IF Statements ''' |
Revision as of 11:23, 26 May 2017
Contents
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 information from users that run a Python script, such as a username or password.
- Process the inputted information using Logic 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.
- Process the inputted information 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.
INVESTIGATION 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.
Storing User Input In Variables
- Perform the following steps:
- Launch your Centos VM, open a shell terminal (as a regular user) and start a new ipython3 session:
ipython3
- 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:
#!/usr/bin/env python3 name = 'Jon' age = 20 print('Hi ' + name + ', you are ' + str(age) + ' years old.')
- Try running this script inside ipython3 and study the output:This Python script is not very useful: it displays the same output regardless of the number of times that the Python script is run.
run lab2a.py
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. - Return to your ipython3 shell and type the following code (do NOT edit the lab2a.py file, just issue from the shell):
colour = input("Type in a colour and press enter: ")
- When prompted, type the text: red and press ENTER. Did anything display? Why not?
- Issue the following in the ipython3 shell:What was displayed?
print(colour)
- Issue the following in the ipython3 shell:Note what was displayed.
print('The colour I typed in is: ' + colour)
- Exit the ipython3 shell, 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 matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py python3 ./CheckLab2.py -f -v lab2a
- 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.
- Launch your Centos VM, open a shell terminal (as a regular user) and start a new ipython3 session:
Practice Storing User Input
- 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.
- Perform the following Instructions:
- Make a copy of lab2a.py and call it lab2b.py.
- 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 a variable called name
- The script should use a variable 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 variables (case sensitivity counts)
- The script should print the EXACT OUTPUT as shown (case sensitivity counts)
- Sample run 1:
run lab2b.py Name: Jon Age: 20 Hi Jon, you are 20 years old.
- Sample run 2:
run lab2b.py Name: Jen Age: 25 Hi Jen, you are 25 years old.
- 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 matrix.senecac.on.ca/~acoatley-willis/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.
- Sample run 1:
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.
Perform the following steps:
- Access your ipython3 shell:In order to read arguments in Python, we will need to import special variables 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 in our program. This is done by issuing the import sys function within your ipython3 shell.
ipython3
- Issue following to access your ipython3 shell and import special variables:
import sys
- 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 (in fact, inspect other items other than libraries) in order to refer to functions and values that are available. Issue the following function:You may feel overwhelmed with all of this information, but not to worry, there are additional tools and tips on how to obtain information regarding these functions contain in the library.
dir(sys)
- Issue the following functions and note what they do:Note that the sys.exit() function will be useful later in this lab, make sure you write it down in your notes.
print(sys.version) # tells us our python version print(sys.platform) # tells us our operating system platform print(sys.argv) # tells us our arguments or shell version if 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 function to store data as a result of running the Python script with arguments. The sys.argv function, when used within your Python script can store the following:- sys.argv - stores all argument data
- 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...
- 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)
- Run the script and examine the output by running the Python script without and with arguments:
run showargs.py run showargs.py testing different arguments run showargs.py argument1 argument2 argument3
- Access your ipython3 shell:
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:
- 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)
- Sample run 1:
run lab2c.py Jon 20 Hi Jon, you are 20 years old.
- Sample run 2:
run 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:
run 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 matrix.senecac.on.ca/~acoatley-willis/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.
- Sample run 1:
INVESTIGATION 2: USING LOGIC STATEMENTS
- In computer programming, control flow statement can be used to change the direction (flow) of a program. 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 (either user input, or command arguments). 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
- Open an ipython3 shell:
ipython3
- Let's create an if statement from the ipython3 shell
Issue the following 2 lines, indenting the second line (you may need to press ENTER a second time for statement to execute):What happened? It is important to note a couple of things with the IF statement:if True: print('This print is apart of the if statement')
- When an IF statement is 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 condition determined true or false.
- 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 as part of the main program. Also, using indentation makes it easier for a programmer to identify Control Flow statements. From this point on, be VERY careful and consistent in the indentation that you make with LOGIC statements.
However, if the LOGIC statement is 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. - Issue the following 3 lines, indenting the second and third lines, but NOT the fourth line:What do you notice?
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')
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 a condition to test in order to render a True or False Boolean value to be used with control flow statements (referred to as: Boolean Logic). - let's create an IF statement that runs under specific conditions. Issue the following code below: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 variable. The IF statement is using that variable (called 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 a variable and may not allow IF statement to properly test the condition! Also note that a space is used to separate arguments with the IF statement. The IF statement tests that condition to see if it is True or False. If that condition is True, it will run the code indented below. On the other hand, if that condition is False, it will not run the code. Try experimenting with different combinations of passwords.
password = input('Please enter a secret password') if password == 'P@ssw0rd': print('You have succesfully used the right password')
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 variables. 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. - Issue the following lines of code:What happened?
import sys print(len(sys.argv)) if len(sys.argv) != 10: print('you do not have 10 arguments') sys.exit()
- Open an ipython3 shell:
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.
- 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 likewise, if not exactly 2 arguments are NOT provided when running script
(NOTE: Use sys.argv[0] value in this message in case you rename the script at a later date!) - The script should use sys.exit() (i.e. to 'abort' script) if zero arguments, or likewise, if not exactly 2 arguments are not provided when running script
- 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:
run lab2d.py Jon 20 Hi Jon, you are 20 years old.
- Sample run 2:
run lab2d.py Jen 25 Hi Jen, you are 25 years old.
- Sample run 3:
run lab2d.py Usage: lab2d.py [name] [age]
- Sample run 4:
run 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 matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py python3 ./CheckLab2.py -f -v lab2d
- Sample run 1:
- 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.
- Perform the following steps
- For the following examples, try changing the numbers in the variables to get different results.
- Open an ipython3 shell:Let's perform an IF statement testing a condition of two variable values. In this case, if variable 'a' is greater than variable 'b', then print a message, if False, do nothing.
ipython3
- Issue the following at the ipython3 shell:What happened? Let's now use an IF/ELSE statement.
a = 10 b = 15 if a > b: print('a is greater than b')
- Issue the following at the ipython3 shell:What happened?
a = 10 b = 15 if a > b: print('a is greater than b') else: print('b is greater than a')
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 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. 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). - Issue the following at the ipython3 shell:
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')
- You are NOT required to create a Python script for this section or run the checking script. Proceed to INVESTIGATION 3.
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, LOGIC 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
- Open ipython3A WHILE loop can be used to create a Determinant Loop. That term means that the number of loops (also referred to as: 'repetitions' or 'iterations') are known or 'determined' in advance. Below is a determinant WHILE loop that will count to 5. Each time the loop is run, it will add one to the count variable, increasing the variables number.
ipython3
- Issue the following at the ipython3 shell to see what happens:A WHILE loop can also be used as an Indeterminant Loop. That term means that the number of loops are unknown in advance. For example, the loop keeps on repeating until the user enters the correct data - we have no idea how many times that user will do that, since that is the job of the user running the script and NOT the programmer. Indeterminant Loops are extremely useful for error-checking in order to prevent incorrect data being accepted and causing the script not to perform correctly.
count = 0 while count != 5: print(count) count = count + 1 print('loop has ended')
- Here is an example of an indeterminant loop for error-checking.
Issue the following at the ipython3 shell 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!')
- Open ipython3
- 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:
- 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:
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 matrix.senecac.on.ca/~acoatley-willis/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.
- Sample run:
PART 2 - Understanding WHILE Loops with 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 simply strings 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:
- Make a copy of lab2e.py and call it lab2f.py.
- 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:
run lab2f.py 10 10 9 8 7 6 5 4 3 2 1 blast off!
- Sample run 2:
run 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 matrix.senecac.on.ca/~acoatley-willis/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.
- Sample run 1:
PART 3 - Using WHILE Loops With IF Statements
Practice Using Loops With IF Statements
- 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])
- WARNING: Remember to check the number of arguments using len(sys.argv) in a if statement
- 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 timer equals 0
- The script should print the EXACT OUTPUT as shown
- Sample run 1:
run lab2g.py 5 5 4 3 2 1 blast off!
- Sample run 1:
- Sample run 2:
run lab2g.py 2 2 1 blast off!
- Sample run 2:
- Sample run 3:
run lab2g.py 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 matrix.senecac.on.ca/~acoatley-willis/CheckLab2.py python3 ./CheckLab2.py -f -v lab2g
- Sample run 3:
- 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.
LAB 2 SIGN-OFF (SHOW INSTRUCTOR)
- 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
- ✓ Lab2 logbook notes completed
- ✓ Output of:
Practice For Quizzes, Tests, Midterm & Final Exam
- x
- x
- x