Difference between revisions of "OPS435 Python Lab 2"

From CDOT Wiki
Jump to: navigation, search
(PART 1 - INPUT)
(PART 1 - USER INPUT)
Line 37: Line 37:
 
</source>
 
</source>
 
:#Before proceeding, make certain that you identify any and all errors in "lab2a.py". When the check script tells you everything is "ok", you may procede to the next step.
 
:#Before proceeding, make certain that you identify any and all errors in "lab2a.py". When the check script tells you everything is "ok", you may procede to the next step.
:#Now it's time to create a new script. Make a copy of '''lab2a.py''' and call it '''lab2b.py'''. Now modify '''lab2b.py''' so that it asks the user for both the value of name and the value of age. Use the input() function and store the values in the correct variables. Example output is shown below:
 
  
::::*The script should have a Shebang line
+
=== Practice - Storing User Input ===
::::*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 correct variables
 
::::*The script should print the EXACT OUTPUT as shown
 
  
Sample run 1:
+
:Now it's time to create a new script. Make a copy of '''lab2a.py''' and call it '''lab2b.py'''. Now modify '''lab2b.py''' so that it asks the user for both the value of name and the value of age. Use the input() function and store the values in the correct variables. Example output is shown below:
  
<source>
+
::*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 correct variables
 +
::*The script should print the EXACT OUTPUT as shown
 +
:::Sample run 1:<source>
 
run lab2b.py
 
run lab2b.py
 
Name: Jon
 
Name: Jon
Line 55: Line 55:
 
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 lab2b.py
 
run lab2b.py
 
Name: Jen
 
Name: Jen
Line 64: Line 61:
 
Hi Jen, you are 25 years old.
 
Hi Jen, you are 25 years old.
 
</source>
 
</source>
 
+
::8. Download the check script and check your work. Enter the following commands from the bash shell.<source>
 
 
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
Line 73: Line 67:
 
python3 ./CheckLab2.py -f -v lab2b
 
python3 ./CheckLab2.py -f -v lab2b
 
</source>
 
</source>
 
+
::9. 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.
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 ==
 
== PART 2 - ARGUMENTS ==

Revision as of 02:25, 25 May 2017

LAB OBJECTIVES

The lab covers the user interaction with programs that we will write. The objectives will be to write programs that can take information from the users, such as a username or password. The next step in these programs is to use the information that the user provides. 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. Finally the lab will go over the procedures for repitition, this 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. Through these 3 investigations you will learn to use: user input/arguments, if/else/logic, and for/while loops.

INVESTIGATION 1: USER INPUT

PART 1 - USER INPUT

This first part will cover how to ask the user running the program for input or data. Though we will not be doing very much with the information provided currently, in later sections this will become a key part of how you change the way a program works.

Storing User Input In Variables

Perform the following steps:
  1. First lets start out with a very basic script. This script will use variables to print out specific information to the screen. Make the script lab2a.py with the following content.
    #!/usr/bin/env python3
    
    name = 'Jon'
    age = 20
    print('Hi ' + name + ', you are ' + str(age) + ' years old.')
  2. Try running this script inside ipython3 and study the output:
    run lab2a.py
  3. This Python script is not very useful, it also gives the same output everytime it runs. In ipython3 lets use the input() function to get information from the user. Place a question or hint as a argument in the input() function, this will aid the user in typing in the correct information.
    colour = input("Type in a colour and press enter: ")
    Type in a colour and press enter: red
  4. Now print out the variable colour and it should contain the value you entered after the prompt.
    print(colour)
    print('The colour I typed in is: ' + colour)
  5. If you didn't get the colour you typed in returned, try the above steps with the input() function again.
  6. 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 lab2a
  7. Before proceeding, make certain that you identify any and all errors in "lab2a.py". When the check script tells you everything is "ok", you may procede to the next step.

Practice - Storing User Input

Now it's time to create a new script. Make a copy of lab2a.py and call it lab2b.py. Now modify lab2b.py so that it asks the user for both the value of name and the value of age. Use the input() function and store the values in the correct variables. Example output is shown below:
  • 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 correct variables
  • The script should print the EXACT OUTPUT as shown
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.
8. 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 lab2b
9. 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

A argument is a value that is passed to a program or passed to a function. In the previous section you passed a argument to the input() function. In this section we will go over the steps of passing a argument to your script, but this time the argument will be passed when we execute your script from the bash shell.

  1. In order to read arguments in Python, we will need to import special variables from the system. This is done very easily.
    ipython3
    import sys
  1. 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.
  1. 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.
    dir(sys)
  1. 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.
    print(sys.version) # tells us our python version
    print(sys.platform) # tells us our operating system platform
    print(sys.argv) # tells us our arguments
    sys.exit() # will immediately end our script when run
  1. 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.


Create a new script '~/ops435/lab2/showargs.py' and place the following content inside
#!/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:

run showargs.py
run showargs.py testing different arguments
run showargs.py argument1 argument2 argument3

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.

lab2c 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:

The script should have a Shebang line The script should 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 The script should print the EXACT OUTPUT as shown

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.

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:

run lab2c.py
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

...
...
...

IndexError: list index out of range


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 lab2c

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: IF 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.

PART 1 - INDENTATION AND IF LOGIC

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.

In ipython3 lets make some if statements and see what happens.

if True:
    print('This print is apart of the if statement')

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.

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')

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.

password = input('Please enter a secret password')
if password == 'P@ssw0rd':
    print('You have succesfully used the right password')

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.

We can also use this to compare numbers, and we will also learn a new function here as well. 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.

import sys

print(len(sys.argv))

if len(sys.argv) != 10:
    print('you do not have 10 arguments')
    sys.exit()

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.


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.

lab2d 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 import sys The script should print a usage message IF additional arguments are not given The script should exit IF two additional arguments are not given 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]

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 lab2d

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

There are many ways to use if statements in more advanced configurations. This section will give a few examples and explain them.

For the following examples, try changing the numbers in the variables to get different results.

Using if statements to do numeric comparisons, if variable 'a' is greater than variable 'b', this if statements condition will be True:

a = 10
b = 15
if a > b:
    print('a is greater than b')

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.

a = 10
b = 15
if a > b:
    print('a is greater than b')
elif a < b:
    print('b is greater than a')

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.

   
a = 10
b = 15
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')


INVESTIGATION 3: LOOPS

In programming loops are sequences of code that are repeated multiple times or until a condition is satisfied.

PART 1 - 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.

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.

count = 0
while count != 5:
    print(count)
    count = count + 1
print('loop has ended')

Here is an example of guessing the correct password:

password = ''
while password != 'P@ssw0rd':
    password = input("Type in a password: ")
print('Congratulations you guessed the correct password!')


lab2e 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 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!

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

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 - WHILE LOOPS WITH ARGUMENTS

lab2f 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.

NOTE: When using arguments as number or performing math on arguments you must wrap them in the int() function: number = int(sys.argv[1])

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!


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

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 3 - WHILE LOOPS WITH IF STATEMENTS

lab2g 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.

NOTE: When using arguments as number or performing math on arguments you must wrap them in the int() function: number = int(sys.argv[1]) NOTE: 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 2:

run lab2g.py 2
2
1
blast off!

Sample run 3:

run lab2g.py
3
2
1
blast off!


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

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)

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
Lab2 logbook notes completed




Practice For Quizzes, Tests, Midterm & Final Exam

  1. x
  2. x
  3. x