Changes

Jump to: navigation, search

OPS435 Online Lab1

17,997 bytes added, 15 January
Task 2: Create a project and make a pull request on GitHub
[[Category:rchan]][[Category:OPS435-Online]]
'''Introduction to git, github.com, and Python'''
= Lab Objectives =
:* Using the "git clone" command to clone a repository into a new directory
= Overview =
:*In this lab, you will create an account on github.com and follow the Github "Hello World guide" to create a new public repository on github to and explore the basic workflow of using github to track and manage revisions of software or other contents. The essential operations provided by Github includes:**creating new repository, :**creating a new branch, :**making changes to files, :**creating a pull request, and :**opening and merging a pull request. :*You will then use the git client (git clone) on matrix.senecacollege.ca to access and download the contents of the repository you created on github. Note: if you have your own Linux VM ready, you can also install and use the git client on your VM.:*You will also use the git client on matrix.senecacollege.ca to clone the repository on github.com which hosts the Python scripts for lab 1. :Study *Finally, study, create and execute the simple Python scripts downloaded from the lab 1 repository.
= Reference=
:* Open a pull request, and
:* Merge your pull request
: Please make the following <font color='red'>changes </font> when following the guide::* name the new repository using your <b><u>Seneca user name </u></b> instead of "hello-world".
:* add your full name, and OPS435 section to the README file, do not post any other personal information there.
:* run the following two commands and capture their output to the named files:
<pre>
git log > ~/ops435/lab1/gitlog.txt
</pre>
<pre>
tree -a > ~/ops435/lab1/repo_tree.txt
</pre>
:* Make sure that gitlog.txt and repo_tree.txt are not emptyand are under the ~/ops435/lab1 directory. Review and study the contents of gitlog.txt and repo_tree.txt :*Download the check script and check your work. Enter the following commands from the bash shell.<source lang="bash"> cd ~/ops435/lab1/ pwd #confirm that you are in the right directory ls -l lab1a.py #confirm that you have the directory for you github repo, the files gitlog.txt and repo_tree.txt ls CheckLab1.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab1.py python3 ./CheckLab1.py -f -v lab0a</source>
= Investigation 2 - Python on Matrix =
* The Python Interpreter understanding the Python language and this is why we are going to learn this programming language in this course.
* The Python Language supports both object-oriented programming and procedural programming paradigms.
* In the The Python programming environmentconsists of a few basic components: language keywords, everything is treated as an object in both programming paradigmssymbols, modules, and data objects.
* The Python Interpreter supports two mode of operations: script mode and interactive mode.
* In interactive mode, the Python interpreter allows us to run python code one statement at a time. Currently, there are two major versions of the Python interpreter available on matrix.senecacollege.ca: version 2 and version3.
* To start an interactive Python version 3 shell, type "python3" at the command prompt.
== Task 1 - Setting up Python environment on Matrix for labs and assignments ===== Part I - Python Versions on Matrix ===
:* You can access the Python Interpreter on Matrix from a Linux machine or a Windows 10 machine.
==== Login to matrix.senecacollege.ca from a CentOS 7 machine ===:<font color='red'>This option won't work after September 1, 2020 as matrix.senecacollege.ca had been moved under Seneca's VPN. The latest version of the openconnect client is need to connect to the Seneca VPN. We are working on the instruction on how to do that. In the mean time, please use the Windows 10 as described below to connect to matrix.</font>:* Login To login to matrix.senecacollege.ca with your you must have a active Seneca user nameaccount.:* Login The following is a screen shot showing the login from a CentOS Linux (host or vm) system with your an active Seneca user name: <br /><br />[[image:centos_ssh.png|Ssh to matrix from Linux]]
==== Login to matrix.senecacollege.ca from a Windows 10 machine ====:* Please follow the instruction at [https://inside.senecacollege.ca/its/services/vpn/studentvpn.html Seneca Student VPN] to download and install the GlobalProtect VPN client and connect to the Seneca VPN to your Windows Machine.
:* Login to matrix.senecacollege.ca with your Seneca user name from Windows 10's run box.<br /><br />[[image:window10_ssh.png|ssh to matrix from Windows 10]]
==== Explore Identify and explore Python versions on Matrix ====:* Once you are on matrix.senecacollege.ca, run the "'''python" ''' command to start a Python version 2 interactive shell at the command prompt. The last line displayed should be "'''>>>"'''. "the '''>>>" ''' sign is referred to as the Python interactive shell prompt.
:** python
:** at the "'''>>>" ''' prompt, type help('keywords') and record the output:** at the '''>>>''' prompt, type help('symbols') and record the output:** type exit() at the "'''>>>" ''' prompt to exit from the Python interactive shell.:* Run the "'''python3" ''' command to start a Python version 3 interactive shell session at the command prompt.
:** python3
:** at the "'''>>>" ''' prompt, type help('keywords') and record the output:** at the '''>>>''' prompt, type help('symbols') and record the output
:** type exit() at the ">>>" prompt to exit from the Python interactive shell.
:* Compare the list of keywords and symbols for Python version 2 and version 3. Which keyword(s) is/are remove from version 2 in version 3?
=== Part II - Create directory structure for Labs and Assignments ======= Create directory structure using BASH commands====
:* Lets setup and reserve the following directories for storing and organizing files for labs and assignments. Execute the following commands at the command prompt:
<pre>
</pre>
==== Verify the directory structure created ====
:* Download the sample.py script from https://github.com/rayfreeping/ops435-lab1 repository to ~/ops435/lab1 directory
:* Study and Explore the sample.py python script and identify the following sections:
:** <source>python3 sample.py 2>/dev/null</source>
:** <source>python3 sample.py test 2>/dev/null </source>
:*Download the check script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab1/
pwd #confirm that you are in the right directory
ls -l ~/ops435/ #confirm that you have create the directory structure under ~/ops435
ls CheckLab1.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab1.py
python3 ./CheckLab1.py -f -v lab0b
</source>
== Task 2 Investigation 3 - exploring and using Python's built-in functions ===== Part I - Interactive (leaning) mode: using the Python Interactive Shell ===:* In this mode, you can instruct the Python Interpreter to execute python statement (or python expression) one at a time, call a function, or display the representation of a python data object.
:* To start the Python version 3 Interactive shell, type the command <source>[raymond.chan@mtrx-node05pd lab1]$ python3</source> at the Linux command prompt.
:* You should get a startup message similar to the following:<source>
</source>
:* Please note that the prompt changed from '''>>>''' to '''help>'''. Try the suggestion and feel free to explore the interactive help utility. Simple press the '''Enter''' key to get out of the interactive help utility.
:* At the '''>>>''' prompt, type '''dir()''' to call the built-in function named '''dir''' without passing any function argument to it. The '''dir()''' function will return a list of data object names known to the Python interpreter at that moment. You should get a list of items similar to the following: <source>
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']
>>>
</source>
:* We are interested in the '''object''' named '''__builtins__''' at this moment. We can ask the Python interpreter to tell us more about the '''__builtins__''' object by passing its name '''__builtins__''' as the function argument to the '''dir()''' function: <source>
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError',
...
ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__',
'__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any',
'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',
'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct',
'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round',
'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip']
</source>
:* The above output shows a list of the so-called '''built-in run-time error codes''' and '''bulit-in function names'''. We are going to learn how to use them effectively in order to save our coding effort when writing Python programs/scripts.
:* Let starts with the following built-in functions:
:** print()
:** help()
:** type()
:* We can learn more about the above built-in functions within the Python interactive shell. Study the output of the following command at the '''>>>''' prompt and keep a record of them for future reference:<source>
>>> help(help)
=== Part II - Script >>> help(execution) mode: creating Python script ===:* print() function
>>> help(type) >>> type(type) >>> type(help) >>> type(print)</source> == Part II - Script (execution) mode: creating Python script ==:* In this part we will start writing our very first python script. The scripts we are going to try will be very basic and it is use to help us practice the language syntax and explore the foundational coding skills, such as: :** sending text to the screen,:** storing value in an data object,=== Task 3 1 - Python script using builtin Functions === ====Creating the "Hello World" Python Script==== You will learn to create a simple python script in this section. This python script will just call the Python builtin function print() to send the text "hello world" to the screen. The "hello world" is an old traditional first program students usually are taught to create, which is based on the first programming example from the first C programming text co-written by Dennis Ritchie, the creator of the C programming language and Brian Kernighan. You will learn how to run the Python script in the Python3 shell as well as to learn how to run the Python script from the bash shell. :'''Perform the following steps:'''  :#Create a new Python file in your ~/ops435/lab1 directory. Call it lab1a.py. The first Python code we will write is going to call the print() function. A function is code that has been defined somewhere. Functions can take arguments, use these arguments in some way, and then usually, but not always, return a result. The first function we will use is the "print()" functions, it's sole purpose is to send data to the screen.<br><br>:#Add the following line into your source code file:<source>print()</source>And run it from the command-line: <source>python3 ./lab1a.py</source>You will notice that nothing is printed even though we called the "print()" function. This is because we didn't pass any arguments to it, lets try again.<br><br>:# Modify your call to print() to include an argument ('hello world'):<br><source>print('hello world') </source>This time we should now see that the python function "print()" has sent something to the screen - the words 'hello world'. In Python a word or a bunch of characters like 'hello world' is called a 'string'. In the above example, a '''string''' was passed as an '''argument''' to the print '''function'''. These words are important for understanding and talking about different aspects of code.<br><br>:# Note that there are similarities between the Python print() function and the Bash echo command, but Python is more picky than bash (which is a good thing). Try to run print without the brackets or without the quotes to see what happens.<blockquote style="margin-left:35px;">{{Admon/tip|Reading errors|One of the things that makes a good programmer is debugging skills. The first and most important debugging technique is reading and understanding error messages. Try to understand what the errors are saying even if you think you already know what the problem is and already have some idea about how to fix it.}}</blockquote><ol><li value="5" style="margin-left:25px;">Write the following code into our Python file. Note the she-bang line at the top of the file to run this script in the python3 environment. You will need to add this she-bang line for all python scripts you create for this course.<source lang="python">#!/usr/bin/env python3'''Description: This program will output "hello world" to the screen.''' # Any line that starts with a "#" is also known as a comment,# these lines are ignored by the python interpreter even if# they contain code. The very first line is called a Shebang line, # it is used to tell the system which interpreter to # use(python2, python3, bash, etc).  print('Hello world')</source><li style="margin-left:25px;">Another way of running a Python program is executing it directly, e.g.: <source>./lab1a.py</source>Note that the file will need execute permissions even though you ran it just fine earlier. Why is that? <li style="margin-left:25px;">Download the check script and check your work. Enter the following commands from the bash shell.<source lang="bash"> cd ~/ops435/lab1/ pwd #confirm that you are in the right directory ls lab1a.py #confirm that you have the lab1a.py script in your directory ls CheckLab1.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab1.py python3 ./CheckLab1.py -f -v lab1a</source><li style="margin-left:25px;">Before moving on to the next step make sure you identify any and all errors in "lab1a.py". When the check script tells you everything is "ok", you may proceed to the next step.</ol> = Investigation 4 - exploring Python's built-in Data Objects =:In Python, a data object is used to store data for use later in the program. This data can be a string, integer, decimal number, characters, etc. We will only be covering '''string''' and '''integer''' objects in this lab. You will learn and use other Python built-in data object types in future labs. == String Objects == :String objects contain text to be used in your program. Examples of strings could be user-names, full-names, item descriptions, etc. We will now demonstrate how to assign a string to an object and how to display contents stored in a string object. :'''Perform the following steps:''' :#Create a python script (called lab1b.py) and first - start with a few simple things to try: :#Let's make a new object containing a value:<source lang="python">name = 'Thomas'</source>:#Print the value to the screen:<source lang="python">print(name)</source>:#Think about why this does something different:<source lang="python">print('name')</source>:#Now lets try something new, we are going to print out the string and concatenate/combine it with another string. The plus sign can be used to join two strings together. However, make sure that the name of your object is always outside the quotes, or it will not resolve to a value.<source lang="python">print('I have a friend named ' + name)</source>:#To gain practice, complete your Python script with the following content and details:::::* The script should have a '''Shebang line''' like you did for your lab1a.py python script::::* The script should use a single object called "name"::::* The value of the "name" object should be "Isaac"::::* The script, when executed, should print out "How old are you Isaac?"::::* Sample run: <source> cd ~/ops435/lab1/ ./lab1b.py How old are you Isaac?</source>Try the checking script as you are working through a script to sometimes get hints.<br><br><ol><li value="7" style="margin-left:25px;">Download and run the checking script. Enter the following commands from the '''bash shell''':<source lang="bash">cd ~/ops435/lab1/pwd #confirm that you are in the right directoryls CheckLab1.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/CheckScripts/CheckLab1.pypython3 ./CheckLab1.py -f -v lab1b</source></li><li style="margin-left:25px;"> Before proceeding, make certain that you identify any and all errors in "lab1b.py". When the check script tells you everything is "ok", you may proceed to the next step.</li></ol> == Integer Objects== :In Python, integer objects are used to store an integer numbers that can be used for mathematical operations (discussed in the next section). Integers do NOT contain decimals, and they can be signed (+ or -) or unsigned. Here we will store integers in a object, perform math operations, and display the results. :'''Perform the following steps:''' :#Create a python script (called lab1c.py) and first - start with a few simple things to try: :#Lets create two new objects, num1 and num2, to play with.<source lang="python">num1 = 5num2 = 10</source>:#You can print the values in those integer objects:<source lang="python">print(num1)print(num2)</source>:#Now we will make a new object called "sum", and try some math:<source lang="python">sum = num1 + num2</source>This will add the values contained in the integer objects together and assign the result to the object named "sum". However you will note that there is no data show up on the screen. Let's inspect the contents of the new object named "sum":<source lang="python">print(sum)</source>Does this value look right? Are you sure?<br>:#Now lets try printing this sum out with a string:<source lang="python">print('The sum is: ' + sum)</source>What happened? Did you receive an error? This may have been the first time you've seen this error, but it won't be the last. What we tried to do is combine a string with a number, and this won't work.<br><br>In order concatenate a sting and an integer object, we will have to use another builtin function called "str()" to convert an integer object to a string first. The "str()" function will return a string of your number and provide it as a argument to "print()". This function will not change the value of your object, your object is still an integer object.<br><br>:# Issue the following:<source lang="python">print('The sum is: ' + str(sum))</source>What did you notice this time?<br />:#To gain practice, complete your python script with the following features::::* string The script should have a Shebang line.:::* The script should have an object called '''name''':::* The script should have an object called '''age''':::* The value of the '''name''' object should be '''Isaac''':::* The object '''age''' should contain a integer:::* The value of the '''age''' objectshould be '''72''':::* The script, when executed, should print out "Isaac is 72 years old!":::Example run: <source>cd ~/ops435/lab1/./lab1c.pyIsaac is 72 years old!</source><br>Try the check script as you are working through a script to sometimes get hints.<br><ol><li value=10" style="margin-left:25px;">Download and run the checking script. Enter the following commands from the bash shell:<source lang= Task 4 "bash">cd ~/ops435/lab1/pwd #confirm that you are in the right directoryls CheckLab1.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab1.pypython3 ./CheckLab1.py -f -v lab1c</source></li><li style="margin-left:25px;">Before moving on to the next step make sure you identify any and all errors in "lab1c.py". When the check script tells you everything is "ok", you may proceed to the next step.</li></ol> = Investigation 5 - exploring on how to get Python to do maths =:In the previous section, you performed a couple of simple mathematical operations. In this section, you will learn some additional mathematical operations.  :'''Perform the following steps:''' :# Try some of the following to see what happens in Python:<source lang="python">print(10 + 5) # additionprint(10 - 5) # subtractionprint(10 * 5) # multiplicationprint(10 / 5) # divisionprint(10 ** 5) # exponents</source>NOTE: You must be careful when combining more complex math operators together. Python uses '''PEMDAS''' ('''P'''arentheses, '''E'''xponents, '''M'''ultiplication and '''D'''ivision, '''A'''ddition and '''S'''ubtraction) to resolve math.<br><br>:# Go over the below examples and see if you understand each situation:<source lang="python">print(10 + 5 * 2) # multiplication happens before additionprint((10 + 5) * 2) # parentheses happen before multiplicationprint(10 + 5 * 2 - 10 ** 2) # first exponents, then multiplication, then addition and subtraction from left-to-rightprint(15 / 3 * 4) # division and multiplication happen from left-to-rightprint(100 / ((5 + 5) * 2)) # the inner most parentheses are first performing addition, then parentheses again with multiplication, finally the division </source>:#To gain practice, complete your script with the following content and details:::* The script should have a Shebang line.::* The object '''x''' should contain a integer with the value '''10'''::* The object '''y''' should contain a integer with the value '''2'''::* The object '''z''' should contain a integer with the value '''5'''::* The script, when executed, should print out "10 + 2 * 5 =20" (the printout should change if the values in the objects change):::Example run: <source>cd ~/ops435/lab1/./lab1d.py10 + 2 * Math operators5 = 20</source>Try the checking script as you are working through a script to sometimes get hints.<br><br><ol><li style="margin-left:25px;" value="4">Download and run the checking script. Enter the following commands from the bash shell:<source lang="bash">cd ~/ops435/lab1/pwd #confirm that you are in the right directoryls CheckLab1.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/master/LabCheckScripts/CheckLab1.pypython3 ./CheckLab1.py -f -v lab1d</source>Before moving on to the next step make sure you identify any and all errors in "lab1d.py".<br><br></li><li style="margin-left:25px;">When the check script tells you everything is "ok", you may proceed to the next step.<br><br></li></ol>
=LAB 1 SIGN-OFF Upload the following files individually to Blackboard=
:* gitlog'''Run the CheckLab1.py script and capture the result'''<source>python3 ./CheckLab1.py -f -v &> lab1_[seneca_id].txt</source> : contains Submit the output of the command "git log" from Task 3following files individually to Blackboard::* repo_tree.txt: contains the output of the command <span style="tree color:green;font-asize:1.5em;" from Task 3>&#x2713;</span> <code>lab1_[seneca_id].txt</code>:* lab1_check.txt: contains the output of the command <span style="python3 color:green;font-size:1.5em;">&#x2713;</checkLab1span> <code>gitlog.txt, repo_tree.txt, lab1a.py, lab1b.py lab1c.py -f -v", lab1d.py</code>
= Lab Review =
:# What is the name of the definitive branch in a git repository?
:# What is a "pull request" related to a branch in a git repository?
:# Write Python code that when run, will perform the following tasks:<ol type="a"><li>Contain a she-bang line</li><li>Display a greetings message to the user</li><li>display an empty line ('''hint:''' use the special character '''\n''' to print the a new-line character)</li><li>Display text, '''"Your current directory is:"''' (You are NOT required to display quotation marks)</li><li>Display the current working directory pathname (using an appropriate command)</li><li>Display another empty line</li></ol>
:# How do you execute a Python script when you are within the interactive <u>python3</u> shell? (Hint: make use of a function provided by the os python module.)
:# How do you execute a Python script when you are in the <u>Bash</u> Shell (i.e. NOT within the python3 shell)?
:# Write the pipeline command to check if the CheckLab1.py checking script exists, and download it from the location:<br>https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab1.py
1,687
edits

Navigation menu