Difference between revisions of "OPS435 Python Lab 1"

From CDOT Wiki
Jump to: navigation, search
(Part 1 - Choosing Your Linux Distribution)
 
(478 intermediate revisions by 5 users not shown)
Line 1: Line 1:
= Lab Preparation =
+
<font color='red'>
 +
'''** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **'''
 +
</font>
 +
= LAB OBJECTIVES =
  
== Purpose/Objectives ==
+
:In this lab, you will install a current distribution of Linux in a Virtual Machine on your external SSD. You will do all of your future work within this VM (including quizzes!). You will then setup your Python scripting environment on your host machine, including the setup the of '''python''' libraries and also the setup of a user-friendly interactive Python environment called '''ipython'''. You will also install additional framework tools (such as '''git''', '''vim''', and '''tmux''') to be used in later labs.
  
Selecting, installing, and setting up your Linux Distribution environment. Learning basics of interacting with python.
+
:After selecting an appropriate text editor to use, then you will start to create '''Python''' scripts to learn basic operations such as: '''printing text''', '''using objects''', and performing '''math operations'''.
 +
<br><br>
  
= Investigation 1 - Installing Linux =
+
= INVESTIGATION 1: INSTALLING LINUX VM=
  
=== Part 1 - Choosing Your Linux Distribution ===
+
=== PART 1 - Installing Your Linux Distribution ===
  
 
<!-- Try to use tables and simplify the layers of WIKI to make top links less verbose to students -->
 
<!-- Try to use tables and simplify the layers of WIKI to make top links less verbose to students -->
 +
 +
:Centos 7 - release 1810 will be used for this course. The purpose for this is to allow you to use a consistent and stable '''RedHat''' based OS, and to lower the amount of new linux distros that you need to learn.
  
Since Python runs independently regardless the of the Linux distribution, you have some flexibility of which Linux OS to use. Below is a table displaying the characteristics of the Centos vs Fedora distributions and related Python packages.
+
: Most of you will likely use the school's Windows machines with the Vmware hypervisor. It is also possible to use your own computer, but check with your professor before you do that.
  
<table border="1" cellspacing="0" cellpadding="5" >
+
:Centos 7 comes with python 2.7, for this course we will be primarily using Python3. However, not practicing python 2.7 would be a mistake, since so many programs and operating systems still depend on Python2. It is recommended that students note general improvements/differences in Python2 and Python3.
<tr><td>'''Linux Distribution'''</td><td>'''Characteristics'''</td><td>'''Python Version'''</td></tr>
 
<tr><td valign="top">'''Centos7'''</td><td valign="top">The stable version of Centos 7 - release 1151 will be chosen(tested) to be supported for this course. This is to keep the ops stream on red hat based systems, lower the amount of new linux distros that need to be learned by students. This should be the default choice for this course, as it allows for the course to run longer before getting outdated with new software and updates.</td><td>Centos 7 comes with python 2.7, which means that it is not optimal out for the box for teaching this course. However not teaching python 2.7 would be a mistake since so many programs and operating systems still depend on python 2. It would be good to note some changes and encourage new work to be done in python3 while paying attention to specific projects that work only with python 2.</td></tr>
 
<tr><td valign="top">'''Fedora'''</td><td valign="top">Fedora will always be the slightly harder distribution to support for a course, so it would be great to have a alternative that is stable. The Fedora distribution has a much larger set of packages throughout its repositories, while this is usually not advantageous for a server context, it can work very well with developers. As students write code they may want more customized environments and coding applications, some of these applications may be harder to get on a server distribution. The other benefit to using Fedora is gaining experience using newer software, by practicing with newer software, students will be exposed to changes they will see in much later Centos releases.</td><td>The most recent version of Fedora is a great pick for python development since they've switched the default python installed to python3, which is primarily what this course is about. However,this may cause issues as we get to Ansible or Openstack so we will have to cover the differences between python2 and python3 including a python2 installation on Fedora.</td></tr></table>
 
  
After choosing your Linux distribution to use for these labs, install the latest graphical version of that Linux OS.
+
 
 +
:'''<u>Centos 7 VM Details / Minimum Requirements:</u>'''
 +
 
 +
::*'''Name:''' centos7
 +
::*'''Boot media / Installation:''' CentOS7 Full Install DVD
 +
:::*Download at Seneca College: CentOS 7 Full Install DVD (image file): http://belmont.senecacollege.ca/pub/centos/7/isos/x86_64/CentOS-7-x86_64-DVD-1810.iso
 +
:::*Download outside Seneca College: http://mirror.csclub.uwaterloo.ca/centos/7/isos/x86_64/CentOS-7-x86_64-DVD-1810.iso
 +
::*'''Disk space:''' 50GB
 +
::*'''CPUs:''' 4 (Number of processors: 1, Number of cores per processor: 4)
 +
::*'''Internal Memory:''' 8GB
 +
::*'''Environment:''' GNOME Desktop
  
 
<!--==== Environment Setup ====
 
<!--==== Environment Setup ====
Line 36: Line 49:
 
-->
 
-->
  
'''Perform the following steps:'''
 
  
=== Part 1 - Lab Check lab0a ===
+
:'''Perform the following steps:'''
  
This course is designed with a unit testing suite, which can be used to look at the scripts you write and give real-time feedback. This feedback is not perfect, however it may offer some hints if you get stuck with a error. It can also be used to make sure you are on the right track, and show progress.
+
:#Regardless of the Linux distribution that is used for this course, these lab will be using and referring to the current version of '''CentOS 7''' (Graphical Desktop) for our main Linux machine. When creating your VM, refer to the '''Details / Minimum Requirements''' section above for assistance.
 +
:#Install CentOS 7 VM selecting the default partitions. When you have finished the installation of CentOS 7, you may proceed to the next step.
 +
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Unit Feedback Scripts|Each '''Part''' (within an 'Investigation) is referred to as a '''Unit'''. Each Unit will require that the student download and run a '''Unit Feedback Script''', which provides the OPS435 student "real-time feedback" of their completed work.<br>This feedback is not considered to be perfect or fool-proof; however, it may provide feedback (hints) in case a student gets stuck or experiences an error when performing administration tasks or when creating their Python scripts. These unit feedback scripts can also be used to confirm that the student's Python script is on the right track, and provide a consistent record of their Python scripting progress throughout their labs.}}</blockquote>
  
Download the check script. Enter the following commands from the bash shell.
+
<!--<ol><li value="3" style="margin-left:25px;">Issue the following commands (as a regular user) in order to setup, download and run the first unit feedback script:<br><source lang="bash">
<pre>
+
mkdir -p ~/ops435/lab1/
 
cd ~/ops435/lab1/
 
cd ~/ops435/lab1/
pwd #confirm that you are in the right directory
+
pwd #   <-- i.e. confirm that you are in the correct directory
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
+
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
 
python3 ./CheckLab1.py -f -v lab0a
 
python3 ./CheckLab1.py -f -v lab0a
</pre>
+
</source></li>
 
+
<li style="margin-left:25px;">Before moving on to the next step make sure you identify any and all errors from the check script.<br>When the check script tells you everything is "ok" for "lab0a", you may proceed to the next step.<br><br></li></ol>-->
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.
 
 
 
== Part 2 - Environment Setup ==
 
 
 
It's time to install applications and setup your environment.
 
 
 
 
 
The first step is to update our entire system. Fedora uses a new package manager, it is based on yum, but has newer code, more maintainers and many improvements. It should work very similarly to the yum command, but check the man pages if you get confused.
 
<pre>dnf update</pre>
 
  
Lets start installing applications we need, first Python version 3 and version 2.
+
=== PART 2 - Setting up Your Python Environment For Labs ===
<pre>
 
dnf install python3 python2 # Install python3.5 and python2.7
 
</pre>
 
  
This next couple applications are tmux and screen. They are referred to as terminal multiplexers. If you plan to spend a lot of time in the terminal, this powerful tool will help you get it done. Lets install it and plan to use it later.
+
In order to learn how to use python on your Linux machine, it is important to setup your Linux environment and learn how to interact with a Python shell. The following should be done on a terminal as the superuser (i.e. root).
<pre>
 
dnf install screen tmux && ln -s /usr/bin/true /etc/sysconfig/bash-prompt-screen
 
</pre>
 
  
We will set our hostname to the Linux Distribution we are using.
 
<pre>
 
hostnamectl set-hostname fedora24 # Set hostname to distribution-name
 
</pre>
 
  
Installing vim(Vi IMproved) will give us syntax highlighting and allow for advanced customization for terminal editing.
+
:'''Perform the following steps:'''
<pre>
 
dnf install vim-common vim-enhanced # Install vim
 
</pre>
 
  
Python pip is a package manager specifically for Python. While it is usually not recommended to install software outside of dnf or yum, sometimes the only way to get a specific or latest version will be through pip.  
+
:#The first step is to update your entire system. <source lang="bash">
<pre>
+
yum update
dnf install python-pip python3-pip # Install pip
+
</source>
</pre>
+
:#Install extra packages for enterprise linux:<source lang="bash">
 +
yum install epel-release
 +
</source>
 +
:#Next install applications that we required, first Python version 3 and version 2:<source lang="bash">
 +
yum install python34 python34-devel # Install python3.4 and python3.4 development libraries
 +
yum install python python2-devel # Install python2.7 and python2.7 development libraries
 +
</source>
 +
:#We now need to create a link to python3.4:<source lang="bash">
 +
cd /bin
 +
ln -s python3.4 python3
 +
</source>
 +
:#Next, you will install a couple of useful applications called '''tmux''' and '''screen'''. They are referred to as '''terminal multiplexers'''. If you plan to spend a lot of time in the terminal, this powerful tool will help you get it done. Lets install it and plan to use it later:<source lang="bash">
 +
yum install screen tmux && ln -s /usr/bin/true /etc/sysconfig/bash-prompt-screen
 +
</source>
 +
:# Set your hostname to the Linux Distribution we are using in case you did not set it correctly during the install process:<source lang="bash">
 +
hostnamectl set-hostname centos7 # Set your hostname to distribution-name
 +
</source>
  
Git is a version control system that allows you to track any changes made to files and programs. The benefit to using git is primarily found when it's used with multiple people, sharing and working on code together. While that is not how we will be using it in this course, you may find some benefits in using it for managing multiple versions of the same program or for backing up your code onto the internet. Check out bitbucket for a free private code repository.
+
::You will be required to use a text editor in order to create and modify your Python scripts. There are many text editors that provide various features to become more comfortable and productive during your Python coding sessions.  
<pre>
+
::Below is a listing of several common text editors and their features.
dnf install git # Install git command line tool
+
<blockquote style="margin-left:35px;">{{Admon/tip|style="padding-left:25px"|Selecting an Appropriate Text Editor|
</pre>
+
'''Geany''' (recommended text editor for labs)<br>A simple graphical text editor for developers. It is available in the CentOS package repositories.<br>
 +
'''Vim'''<br>vim is a powerful text editor for system administration and programming tasks. All of the shortcuts and commands you've learned over the years will help you edit programs efficiently.<br>
 +
'''Sublime'''<br>Another powerful and popular text editor designed for programming. Is not free or open source.}}</blockquote>
  
IPython will be one of the tools we will use the most. Lets install it. You will learn more about it in the next section.
+
<ol><li value=6" style="margin-left:25px;">'''Python pip''' is a package manager specifically for Python. While it is usually not recommended to install software outside of '''dnf''' or '''yum''', sometimes the only way to get a specific or latest version will be through pip:<source lang="bash">
<pre>
+
yum install python-pip # Install python2.7 pip
dnf install python-ipython python3-ipython # Install enhanced interactive python
+
yum install python34-pip # Install python3.4 pip
</pre>
+
</source></li>
 +
<li style="margin-left:25px;">Upgrade python34-pip with the following command:<source lang="bash">
 +
pip3.4 install --upgrade pip
 +
</source></li>
 +
<li style="margin-left:25px;">Issue the following command to install '''git''':<source lang="bash">
 +
yum install git # Install git command line tool
 +
</source></li></ol>
  
==Part 2 - Lab Check lab0b ==
+
<blockquote style="margin-left:35px;">{{Admon/tip|What is a Git?| '''Git''' refers to a '''version control system''' that allows you to track any changes made to files and programs. Our primary use for git in this course will be for backup onto to the internet. Check out '''bitbucket''' for a free private code repository.}}</blockquote>
  
<pre>
+
<ol><li value="8" style="margin-left:25px;">IPython will be one of the tools we will use the most. Lets install it. You will learn more about it in the next section:<source lang="bash">
 +
yum install python-ipython # Install ipython for python2.7
 +
pip3.4 install ipython  # Install ipython for python3.4
 +
</source></li>
 +
<li style="margin-left:25px;">Exit from the superuser shell to your regular user shell and issue the following commands to check your work for this section:<source lang="bash">
 +
mkdir -p ~/ops435/lab1/
 
cd ~/ops435/lab1/
 
cd ~/ops435/lab1/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
+
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
 +
python3 ./CheckLab1.py -f -v lab0a
 
python3 ./CheckLab1.py -f -v lab0b
 
python3 ./CheckLab1.py -f -v lab0b
</pre>
+
</source></li>
 +
<li style="margin-left:25px;">Before moving on to the next step, make sure you identify and correct any and all errors in "lab0b" output. When the check script tells you everything is "ok", you may proceed to the next step.</li></ol>
 +
<br><br>
  
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 procede to the next step.
+
= INVESTIGATION 2: USING THE "IPYTHON" CLI =
  
 +
:'''IPython''' is an interactive environment that allows us to run python code line by line as we write it. This will also act like a bash shell prompt allowing users to enter a limited number of Bash shell commands. You will notice this by seeing an [IN] prompt where to enter commands and an [OUT] prompt that will display output from issued commands. We will start creating scripts out of the code within this '''IPython''' environment.
 +
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|ipython and python|[https://plot.ly/python/ipython-vs-python/ What is the difference between '''python''' and '''ipython'''?] Please note that in later labs, you can use either '''python''' or '''ipythone''' as the interactive python shell.}}</blockquote>
  
  
 +
=== PART 1 - Common Ipython Commands and Features ===
  
== Part 3 - Text Editors ==
+
==== Using Magic Functions ====
  
There are a wide range of text editors for the python language and just about any of them will do. As long as you get basic syntax highlighting and automatic indenting out of the application you are good to go. This section will go over a number of different text editors, showing off a few different text editors so students may find their favourite. There are no wrong answers here, give them all a try and use your favourite.
+
:Lets begin by running some python code in the ipython interactive shell. This is a advanced python shell, similar to the bash shell that you have been using throughout the Linux courses. Throughout these labs the term command can also refer to these "magical functions".
  
=== Vim Editor ===
+
:'''Perform the following steps:'''
  
As a system administrator you have probably spent a ton of time inside vim. Well vim is just as powerful and useful when you get to programming, all the shortcuts and commands you've learned over the years will help you edit programs efficiently. On top of what you already know, it might be time to customize vim a little more for programming. Vim can actually be modified to become a full programming environment with all the features you yould expect.
+
:#Make sure you're using your regular user login and not using the root user for the following section.
 
+
:#To access the '''ipython''' shell, issue the following command:<source>
=== Atom Editor ===
+
ipython3
 
+
</source>Now we are now inside the IPython environment. We can run some basic bash commands within this shell by issuing IPython magic functions. <br>
"A hackable text editor for the 21st Century". This text editor is a powerful tools that comes with everything your need right out of the box. Atom allows for deep customization from everything from complete functionality changes to just changing the theme. Definitely worth checking out, especially for python development.  
+
:#Lets try a few commands out now:<source>
 
+
ls
=== Sublime ===
+
pwd
 
+
cd ~/
Sublime is a popular text editor with tons of customizations and themes.
+
ls
 
+
</source>'''Remember:''' You are not using Python here, instead, these are aliases for Bash shell commands that IPython gives you access to. What you are actually using is bash, but not all bash commands are available in the IPython environment.<br><br>
=== More ===
+
:#Lets find out which ones are available, type the following command into the IPython shell:<source>
 +
alias
 +
</source>We should now have a list of all the bash commands available in IPython.
 +
:#Lets setup a directory structures for completing and organizing labs. These should be the locations to store your lab scripts.<source>
 +
mkdir ~/ops435/lab2
 +
mkdir ~/ops435/lab3
 +
mkdir ~/ops435/lab4
 +
mkdir ~/ops435/lab5
 +
mkdir ~/ops435/lab6
 +
mkdir ~/ops435/lab7
 +
mkdir ~/ops435/lab8
 +
</source>
 +
:#If you are interested in finding more information about other magic functions in IPython, then within the IPython shell, and enter the following (press the letter '''q''' to exit this function):<source>
 +
magic
 +
</source>
  
Suggest some more.
+
:::This resource will appear OVERWHELMING (a huge amount of information)! As we move throughout this course, you will slowly use different magic functions from here, but we will never use all of them. They cover a huge range of different tasks, while we are writing code, allowing us to interactively inspect the Python we are writing and running. Lets move on for now.
  
== Part 3 - Lab Check lab0c ==
+
<ol><li value="6" style="margin-left:25px;">Issue the following command to exit your ipython session:<source>
 +
exit
 +
</source>
 +
</li>
 +
:In the future see if '''ctrl-d''' works instead of issuing the exit command to quit the ipython shell.
 +
</li>
  
<pre>
+
<li style="margin-left:25px;">
 +
Perform the following steps to evaluate this unit. Run these check scripts regularly as you work through the labs, they may give you hints if you get stuck.</li>
 +
:<source lang="bash">
 
cd ~/ops435/lab1/
 
cd ~/ops435/lab1/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
+
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
 
python3 ./CheckLab1.py -f -v lab0c
 
python3 ./CheckLab1.py -f -v lab0c
</pre>
+
</source>
 
+
</ol>
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 procede to the next step.
+
<br><br>
 
 
 
 
 
 
 
 
= Investigation 2 - IPython =
 
 
 
IPython is an interactive environment that allows us to run python code line by line as we write it. This will function almost exactly like a bash shell prompt, enter a command and recieve the output back. However the commands that we will be running are lines of python code. Using this method we will start creating scripts out of the code we build in the IPython environment.
 
 
 
 
 
== Part 1 - Using IPython ==
 
 
 
=== Using Magic Functions ===
 
 
 
Lets start with trying to run some python code in a interactive shell. This is a advanced python shell, similar to the bash shell that you have been using throughout the linux courses.
 
 
 
To get into the ipython shell type:
 
 
 
<pre>
 
ipython3
 
</pre>
 
 
 
Now we are inside the IPython environment. We can run some basic bash commands in here, this is done through by using IPython magic functions.
 
 
 
Lets try a few commands out now:
 
<pre>
 
%ls
 
%pwd
 
%cd ~/
 
%ls
 
</pre>
 
 
 
Now hold on. You are not using Python here. These are aliases, that IPython gives you access to. What you are actually using is bash, but not all bash commands are available in the IPython environment.
 
 
 
Lets find out which ones are available, type the following command into the IPython shell:
 
 
 
<pre>
 
%alias
 
</pre>
 
 
 
We should now have a list of all the bash command available in IPython. Shortly we will go over how to add new bash commands into this environment, but you must remember, these are only here to assist in your python scripting, we are not here to learn bash commands.
 
 
 
Next lets add a new bash command that seems to be missing from this list:
 
 
 
<pre>
 
%alias vim vim
 
</pre>
 
 
 
The vim command will give us our much needed syntax highlighting, while we are editing scripts from within the IPython environment. These magic %alias functions do not save in between sessions, this creates a problem since you would have to create them every time you start IPython. This will create a error.
 
 
 
<pre>
 
exit
 
ipython3
 
vim
 
</pre>
 
 
 
You should be seeing an error telling you invalid syntax. This is happening because we need to create a config file to make this alias persist inbetween sessions.
 
 
 
Exit your current IPython session:
 
<pre>
 
exit
 
</pre>
 
 
 
Create a new file and add the following content to it:
 
 
 
<pre>
 
vim ~/.ipython/profile_default/startup/00-alias.ipy
 
<pre>
 
 
 
Place our alias inside:
 
<blockquote>
 
%alias vim vim
 
</blockquote>
 
  
Save and quit the file. Now lets return to our IPython shell and confirm that our alias is available right away.
+
= INVESTIGATION 3: WRITING PYTHON SCRIPTS =
  
<pre>
+
:In this investigation we will start writing our very first python scripts. These will be very basic and help us practice syntax and foundation skills, such as: outputting text to the screen, storing data inside objects, and using math operators.
ipython3
 
%vim
 
</pre>
 
  
At this point vim should open successfully and you should now understand how to create new IPython aliases and store them persistently. Exit vim now and head back to the IPython shell.  
+
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Object and Variable|The terms '''object''' and '''variable''' are used to refer to a data item in computer programming. The term '''variable''' are mostly used in 3rd generation programming/scripting languages (e.g. bash) while the term '''object''' is preferred in object oriented programming/scripting languages like Python. In the context of Python programming/scripting, When you see the term '''variable''' in the lab instructions, it can be replaced by the term '''object'''.}}</blockquote>
  
Lets setup a directory structures for completing and organizing labs. These should be the locations to store your lab scripts.
 
  
<pre>
+
=== PART 1 - Common Introductory Python Functions ===
%mkdir ~/ops435
 
%mkdir ~/ops435/lab1
 
%mkdir ~/ops435/lab2
 
%mkdir ~/ops435/lab3
 
%mkdir ~/ops435/lab4
 
%mkdir ~/ops435/lab5
 
%mkdir ~/ops435/lab6
 
%mkdir ~/ops435/lab7
 
%mkdir ~/ops435/lab8
 
</pre>
 
  
If you are interested in finding more information about magic functions in IPython, try entering the IPython shell and typing the following:
+
====Creating the introductory "Hello World" Script====
<pre>
 
%magic
 
</pre>
 
  
This should show you a OVERWHELMING amount of information, as we move through the course we will slowly use different magic functions from here, but we will never use all of them. To be continued. Magic functions than just running bash commands. They cover a huge range of different tasks, while we are writing code, allowing us to interactively inspect the Python we are writing and running. Lets move on for now.
+
You will learn to create a simple python script in this section. This python script will just print the text "hello world". The "hello world" 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 learn how to run the python script from the bash shell.
  
== Part 1 - Lab Check lab1a ==
+
:'''Perform the following steps:'''
  
<pre>
 
cd ~/ops435/lab1/
 
pwd #confirm that you are in the right directory
 
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
 
python3 ./CheckLab1.py -f -v lab1a
 
</pre>
 
  
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 procede to the next step.
+
:#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 in another location. Functions can take arguments, use these arguments in some way, and then usually return a result. The first function we will use is the "print()" functions, it's sole purpose is to output information to the screen.<br><br>
 
+
:#Add the following line into your source code file:<source>
 
 
= Investigation 3 - Writing a Python Script =
 
 
 
During this investigation we will start writing our very first python scripts. These will be very basic and help us practice syntax and foundational skills, such as: outputing text to the screen, storing data inside variables, and using math operators.
 
 
 
== Part 1 - Printing ==
 
 
 
Lets start IPython interpreter and start writing some python code.
 
 
 
<pre>
 
ipython3
 
%cd ~/ops435/lab1
 
%pwd
 
%ls
 
</pre>
 
 
 
Our first python code we will write is the print function. A function is code that has been defined in another location. Functions can take arguments, use these arguments in some way, and then usually return a result. The first function we will use is the "print()" functions, it's sole purpose is to output information to the screen.
 
 
 
<pre>
 
 
print()
 
print()
</pre>
+
</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 inlcude an argument ('hello world'):<br><source>
You will notice that nothing happened when we ran this "print()" function. This is because we didn't pass any arguments to it, lets try again.
 
 
 
<pre>
 
 
print('hello world')
 
print('hello world')
</pre>
+
</source>This time we should now see that the python function "print()" has outputted 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 a '''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.
This time we should now see that the python function "print()" has outputted to the screen the words 'hello world'. In python a word or a bunch of characters like 'hello world' is called a 'string'. So what we did above is, passed a '''string''' as a '''argument''' to the print '''function'''. These words are important for understanding and talking about different aspects of code.
+
<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">
 
 
== Part 2 - Hello World ==
 
 
 
Next, we will make our first script with the above function. Open a new text file called "lab1a.py".
 
 
 
<pre>
 
%vim ~/ops435/lab1/lab1a.py
 
</pre>  
 
 
 
Write the following code into our python file.  
 
<pre>
 
 
#!/usr/bin/env python3
 
#!/usr/bin/env python3
  
Line 305: Line 225:
  
 
print('Hello world')
 
print('Hello world')
</pre>
+
</source>
 
+
<li style="margin-left:25px;">Another way of running a pythion program is executing it directly, e.g.: <source>./test.py</source>Note that the file will need execute permissions even though you ran it just fine earlier. Why is that?
Save the file and quit vim. We will now go over the process of manually running this python script. Both in the Bash shell and in the IPython shell.
+
<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
Now lets try running the script directly from the IPython shell.
+
ls lab1a.py #confirm that you have the lab1a.py script in your directory
 
+
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
<pre>
+
python3 ./CheckLab1.py -f -v lab1a
ipython3
+
</source>
%run ~/ops435/lab1/lab1a.py
+
<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.
</pre>
+
</ol>
 
 
Your python script should have run, if you have any errors you should check that you typed the script in exactly. Be careful of extra spaces, symbols, letters, or lowercase/uppercase differences.
 
 
 
Exit out of IPython. Now from the Bash shell we will give it the correct linux permissions and run it. This is just showing the multiple ways you can use this python script. You are not required to have IPython running on a system, however hopefully we can use IPython's powerful features to our advantage.
 
 
 
<pre>
 
exit
 
</pre>
 
 
 
<pre>
 
chmod 755 ~/ops435/lab1/lab1a.py
 
python3 ~/ops435/lab1/lab1a.py
 
</pre>
 
 
 
=== Part 2 - Lab Check lab1a ===
 
 
 
This course is designed with a unit testing suite, which can be used to look at the scripts you write and give real-time feedback. This feedback is not perfect, however it may offer some hints if you get stuck with a error. It can also be used to make sure you are on the write track, and show progress.
 
 
 
Download the check script. Enter the following commands from the bash shell.
 
<pre>
 
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 matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
 
python3 ./CheckLab1.py -f -v lab1a
 
</pre>
 
  
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.
+
=== PART 2 - Working with Python Objects ===
  
== Part 3 - Variables ==
+
:In Python, an 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''' variables in this lab. You will learn and use other python object types in future labs.
  
A variable is used to store data for use later in the program. This data can be a string, integer, decimal, etc.
+
==== String Objects ====
  
=== Part 3 - strings ===
+
: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 to assign a string to an object and how to display contents stored in a string object.
  
First make a new variable containing a value.
+
:'''Perform the following steps:'''
  
<pre>
+
:#Create a python script (called lab1b.py) and first - start with a few simple things to try:
name = 'Thomas'
+
:#Let's make a new object containing a value:<source lang="python">
</pre>
+
name = 'Thomas'
 
+
</source>
Inspect the value.
+
:#Print the value to the screen:<source lang="python">
 
 
<pre>
 
name
 
</pre>
 
 
 
Print the value to the screen.
 
 
 
<pre>
 
 
print(name)
 
print(name)
</pre>
+
</source>
 
+
:#Think about why this does something different:<source lang="python">
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 2 strings together. However, make sure that your variable is always outside the quotes, or it will not resolve to a value.
+
print('name')
 
+
</source>
<pre>
+
:#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 2 strings together. However, make sure that 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)
 
print('I have a friend named ' + name)
</pre>
+
</source>
 
+
:#To gain practice, complete your python script with the following content and details:
=== Part 3 - Evaluation ===
+
::::* 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"
Create a python script: lab1b.py
+
::::* The value of the "name" object should be "Isaac"
* The script should have a Shebang line
+
::::* The script, when executed, should print out "How old are you Isaac?"
* The script should use a single variable called "name"
+
::::*Sample run: <source>
* The value of the "name" variable should be "Isaac"
+
cd ~/ops435/lab1/
* The script, when executed, should print out "How old are you Isaac?"
+
./lab1b.py
 
+
How old are you Isaac?
Example run:  
+
</source>Try the checking script as you are working through a script to sometimes get hints.<br><br>
<pre>
+
<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/
 
%run ./lab1b.py
 
How old are you Isaac?
 
</pre>
 
 
 
Try the check script as you are working through a script to sometimes get hints.
 
 
 
=== Part 3 - Lab Check lab1b ===
 
 
 
This course is designed with a unit testing suite, which can be used to look at the scripts you write and give real-time feedback. This feedback is not perfect, however it may offer some hints if you get stuck with a error. It can also be used to make sure you are on the write track, and show progress.
 
 
 
Download the check script. Enter the following commands from the bash shell.
 
<pre>
 
 
cd ~/ops435/lab1/
 
cd ~/ops435/lab1/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
+
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
 
python3 ./CheckLab1.py -f -v lab1b
 
python3 ./CheckLab1.py -f -v lab1b
</pre>
+
</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>
  
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 procede to the next step.
+
==== Integer Objects====
  
== Part 4 - Integers ==
+
: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.
  
Lets enter into IPython to test out variables.
+
:'''Perform the following steps:'''
<pre>
 
ipython3
 
</pre>
 
  
Lets create some new variables to play with.
+
:#Create a python script (called lab1c.py) and first - start with a few simple things to try:
<pre>
+
:#Lets create some new objects to play with.<source lang="python">
 
num1 = 5
 
num1 = 5
 
num2 = 10
 
num2 = 10
</pre>
+
</source>
 
+
:#You can print the values in those integer objects:<source lang="python">
In IPython we can inspect these variables by just typing the name of the variable. But in a python script this will not provide any output. This feature is useful however for debugging.
+
print(num1)
 
+
print(num2)
<pre>
+
</source>
num1
+
:#Now we will make a new integer object and try some math:<source lang="python">
num2
 
</pre>
 
 
 
Now we will make a new variable and try some math.
 
 
 
<pre>
 
 
sum = num1 + num2
 
sum = num1 + num2
</pre>
+
</source>This will add the values contained in the integer objects together, providing a sum. However you will note that there is no output. Let's inspect the new value:<source lang="python">
 
 
This will add the values contained in the variables together, providing a sum. However you will note that there is no output. First lets inspect the new value.
 
 
 
<pre>
 
sum
 
</pre>
 
 
 
Does this value look right? If we wanted to print this out to the screen we could use the following python code.
 
 
 
<pre>
 
 
print(sum)
 
print(sum)
</pre>
+
</source>Does this value look right? Are you sure?<br>
 
+
:#Now lets try printing this sum out with a string:<source lang="python">
Now lets try printing this sum out with a string.
 
<pre>
 
 
print('The sum is: ' + sum)
 
print('The sum is: ' + sum)
</pre>
+
</source>What happened? Did you receive an error? This will 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 to use display this number as a string we will use the "str()" function on it. 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 interger object.<br><br>
 
+
:# Issue the following:<source lang="python">
What happened? Did you receive an error? This will 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.  
 
 
 
In order to use display this number as a string we will use the "str()" function on it. 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 variable, your variable is still a interger.
 
 
 
<pre>
 
 
print('The sum is: ' + str(sum))
 
print('The sum is: ' + str(sum))
</pre>
+
</source>What did you notice this time?<br />
 
+
:#To gain practice, complete your python script with the following features:
=== Part 4 - Evaluation ===
+
:::* The script should have a Shebang line.
 
+
:::* The script should have an object called '''name'''
Create a python script: lab1c.py
+
:::* The script should have an object called '''age'''
* The script should have a Shebang line.
+
:::* The value of the '''name''' object should be '''Isaac'''
* The script should have a variable called '''name'''
+
:::* The object '''age''' should contain a integer
* The script should have a variable called '''age'''
+
:::* The value of the '''age''' object should be '''72'''
* The value of the '''name''' variable should be '''Isaac'''
+
:::* The script, when executed, should print out "Isaac is 72 years old!"
* The variable '''age''' should contain a integer
+
:::Example run: <source>
* The value of the '''age''' variable should be '''72'''
+
cd ~/ops435/lab1/
* The script, when executed, should print out "Isaac is 72 years old!"
+
./lab1c.py
 
 
Example run:  
 
<pre>
 
%cd ~/ops435/lab1/
 
%run ./lab1c.py
 
 
Isaac is 72 years old!
 
Isaac is 72 years old!
</pre>
+
</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="bash">
Try the check script as you are working through a script to sometimes get hints.
 
 
 
=== Part 4 - Lab Check lab1c ===
 
 
 
This course is designed with a unit testing suite, which can be used to look at the scripts you write and give real-time feedback. This feedback is not perfect, however it may offer some hints if you get stuck with a error. It can also be used to make sure you are on the write track, and show progress.
 
 
 
Download the check script. Enter the following commands from the bash shell.
 
<pre>
 
 
cd ~/ops435/lab1/
 
cd ~/ops435/lab1/
 
pwd #confirm that you are in the right directory
 
pwd #confirm that you are in the right directory
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
+
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
 
python3 ./CheckLab1.py -f -v lab1c
 
python3 ./CheckLab1.py -f -v lab1c
</pre>
+
</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>
  
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 procede to the next step.
+
=== PART 5 - MATH OPERATORS ===
  
 +
:In the previous section, you performed a couple of simple mathematical operations. In this section, you will learn some additional mathematical operations.
  
== Part 5 - Math Operators ==
+
:'''Perform the following steps:'''
  
Python has a number of math operators you can use in your programs.
+
:# Try some of the following to see what happens in Python:<source lang="python">
<pre>
+
print(10 + 5)   # addition
10 + 5    # addition
+
print(10 - 5)   # subtraction
10 - 5    # subtraction
+
print(10 * 5)   # multiplication
10 * 5    # multiplication
+
print(10 / 5)   # division
10 / 5    # division
+
print(10 ** 5)   # exponents
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>
</pre>
+
:# Go over the below examples and see if you understand each situation:<source lang="python">
 
+
print(10 + 5 * 2) # multiplication happens before addition
But you must be careful when combining more complex math operators together. Python uses PEMDAS(Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) to resolve math. Go over the below examples and see if you understand each situation.
+
print((10 + 5) * 2) # parentheses happen before multiplication
 
+
print(10 + 5 * 2 - 10 ** 2) # first exponents, then multiplication, then addition and subtraction from left-to-right
<pre>
+
print(15 / 3 * 4) # division and multiplication happen from left-to-right
10 + 5 * 2 # multiplication happens before addition
+
print(100 / ((5 + 5) * 2)) # the inner most parentheses are first performing addition, then parentheses again with multiplication, finally the division  
(10 + 5) * 2 # parentheses happen before multiplication
+
</source>
10 + 5 * 2 - 10 ** 2 # first exponents, then multiplication, then addition and subtraction from left-to-right
+
:#To gain practice, complete your script with the following content and details:
15 / 3 * 4 # division and multiplication happen from left-to-right
+
::* The script should have a Shebang line.
100 / ((5 + 5) * 2) # the inner most parentheses are first performing addition, then parentheses again with multiplication, finally the division  
+
::* The object '''x''' should contain a integer with the value '''10'''
</pre>
+
::* 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.py
 +
10 + 2 * 5 = 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 directory
 +
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
 +
python3 ./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>
 +
<br><br>
  
 +
= LAB 1 SIGN-OFF (SHOW INSTRUCTOR) =
 +
[[Image:lab1_signoff.png|thumb|right|450px|Students should be prepared with '''all required commands (system information) displayed in a terminal (or multiple terminals) prior to calling the instructor for signoff'''.]]
  
===Part 5 - Evaluation ===
 
  
Create a python script: lab1d.py
+
:'''Have Ready to Show Your Instructor:'''
* The script should have a Shebang line.
 
* The variable '''x''' should contain a integer with the value '''10'''
 
* The variable '''y''' should contain a integer with the value '''2'''
 
* The variable '''z''' should contain a integer with the value '''5'''
 
* The script, when executed, should print out "10 + 2 * 5 = 20"
 
  
Example run:  
+
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>./CheckLab1.py -f -v</code>
<pre>
+
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>cat lab1a.py lab1b.py lab1c.py lab1d.py</code>
%cd ~/ops435/lab1/
 
%run ./lab1d.py
 
10 + 2 * 5 = 20
 
</pre>
 
  
Try the check script as you are working through a script to sometimes get hints.
+
:'''Be able to answer any questions about the lab to show that you understood it!'''
 +
<br>
 +
:'''For sections A & B:'''
  
=== Part 5 - Lab Check lab1d ===
+
::<span style=color:green;font-size:1.5em;">&#x2713;</span> Submit your output and Python scrips via Blackboard instead.
  
This course is designed with a unit testing suite, which can be used to look at the scripts you write and give real-time feedback. This feedback is not perfect, however it may offer some hints if you get stuck with a error. It can also be used to make sure you are on the write track, and show progress.
+
= LAB REVIEW =
  
Download the check script. Enter the following commands from the bash shell.
+
:# Write the command to change the hostname of your Linux machine to '''centos7'''.
<pre>
+
:# What is the purpose of '''git'''? How will git be used in our OPS435 course?
cd ~/ops435/lab1/
+
:# Write the command to create an '''alias''' for the Linux command vim which will be called vi in your ipython3 session.
pwd #confirm that you are in the right directory
+
:# Write the absolute pathname for the ipython3 alias configuration file.
ls CheckLab1.py || wget matrix.senecacollege.ca/~acoatley-willis/CheckLab1.py
+
:# 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>
python3 ./CheckLab1.py -f -v lab1d
+
:# How do you execute a Python script when you are within the <u>ipython3</u> shell?
</pre>
+
:# How do you execute a Python script when you are in the <u>Bash</u> Shell (i.e. NOT within the Ipython3 shell)?
 +
:# Write the pipeline command to check if the CheckLab1.py checking script exists, and download it from the location:<br>https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
  
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 procede to the next step.
+
[[Category:OPS435-Python]]

Latest revision as of 09:25, 21 January 2020

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

LAB OBJECTIVES

In this lab, you will install a current distribution of Linux in a Virtual Machine on your external SSD. You will do all of your future work within this VM (including quizzes!). You will then setup your Python scripting environment on your host machine, including the setup the of python libraries and also the setup of a user-friendly interactive Python environment called ipython. You will also install additional framework tools (such as git, vim, and tmux) to be used in later labs.
After selecting an appropriate text editor to use, then you will start to create Python scripts to learn basic operations such as: printing text, using objects, and performing math operations.



INVESTIGATION 1: INSTALLING LINUX VM

PART 1 - Installing Your Linux Distribution

Centos 7 - release 1810 will be used for this course. The purpose for this is to allow you to use a consistent and stable RedHat based OS, and to lower the amount of new linux distros that you need to learn.
Most of you will likely use the school's Windows machines with the Vmware hypervisor. It is also possible to use your own computer, but check with your professor before you do that.
Centos 7 comes with python 2.7, for this course we will be primarily using Python3. However, not practicing python 2.7 would be a mistake, since so many programs and operating systems still depend on Python2. It is recommended that students note general improvements/differences in Python2 and Python3.


Centos 7 VM Details / Minimum Requirements:
  • Name: centos7
  • Boot media / Installation: CentOS7 Full Install DVD
  • Disk space: 50GB
  • CPUs: 4 (Number of processors: 1, Number of cores per processor: 4)
  • Internal Memory: 8GB
  • Environment: GNOME Desktop


Perform the following steps:
  1. Regardless of the Linux distribution that is used for this course, these lab will be using and referring to the current version of CentOS 7 (Graphical Desktop) for our main Linux machine. When creating your VM, refer to the Details / Minimum Requirements section above for assistance.
  2. Install CentOS 7 VM selecting the default partitions. When you have finished the installation of CentOS 7, you may proceed to the next step.
Important.png
Unit Feedback Scripts
Each Part (within an 'Investigation) is referred to as a Unit. Each Unit will require that the student download and run a Unit Feedback Script, which provides the OPS435 student "real-time feedback" of their completed work.
This feedback is not considered to be perfect or fool-proof; however, it may provide feedback (hints) in case a student gets stuck or experiences an error when performing administration tasks or when creating their Python scripts. These unit feedback scripts can also be used to confirm that the student's Python script is on the right track, and provide a consistent record of their Python scripting progress throughout their labs.


PART 2 - Setting up Your Python Environment For Labs

In order to learn how to use python on your Linux machine, it is important to setup your Linux environment and learn how to interact with a Python shell. The following should be done on a terminal as the superuser (i.e. root).


Perform the following steps:
  1. The first step is to update your entire system.
    yum update
  2. Install extra packages for enterprise linux:
    yum install epel-release
  3. Next install applications that we required, first Python version 3 and version 2:
    yum install python34 python34-devel # Install python3.4 and python3.4 development libraries
    yum install python python2-devel # Install python2.7 and python2.7 development libraries
  4. We now need to create a link to python3.4:
    cd /bin
    ln -s python3.4 python3
  5. Next, you will install a couple of useful applications called tmux and screen. They are referred to as terminal multiplexers. If you plan to spend a lot of time in the terminal, this powerful tool will help you get it done. Lets install it and plan to use it later:
    yum install screen tmux && ln -s /usr/bin/true /etc/sysconfig/bash-prompt-screen
  6. Set your hostname to the Linux Distribution we are using in case you did not set it correctly during the install process:
    hostnamectl set-hostname centos7 # Set your hostname to distribution-name
You will be required to use a text editor in order to create and modify your Python scripts. There are many text editors that provide various features to become more comfortable and productive during your Python coding sessions.
Below is a listing of several common text editors and their features.
Idea.png
Selecting an Appropriate Text Editor

Geany (recommended text editor for labs)
A simple graphical text editor for developers. It is available in the CentOS package repositories.
Vim
vim is a powerful text editor for system administration and programming tasks. All of the shortcuts and commands you've learned over the years will help you edit programs efficiently.

Sublime
Another powerful and popular text editor designed for programming. Is not free or open source.
  1. Python pip is a package manager specifically for Python. While it is usually not recommended to install software outside of dnf or yum, sometimes the only way to get a specific or latest version will be through pip:
    yum install python-pip # Install python2.7 pip
    yum install python34-pip # Install python3.4 pip
  2. Upgrade python34-pip with the following command:
    pip3.4 install --upgrade pip
  3. Issue the following command to install git:
    yum install git # Install git command line tool
Idea.png
What is a Git?
Git refers to a version control system that allows you to track any changes made to files and programs. Our primary use for git in this course will be for backup onto to the internet. Check out bitbucket for a free private code repository.
  1. IPython will be one of the tools we will use the most. Lets install it. You will learn more about it in the next section:
    yum install python-ipython # Install ipython for python2.7
    pip3.4 install ipython  # Install ipython for python3.4
  2. Exit from the superuser shell to your regular user shell and issue the following commands to check your work for this section:
    mkdir -p ~/ops435/lab1/
    cd ~/ops435/lab1/
    pwd #confirm that you are in the right directory
    ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab0a
    python3 ./CheckLab1.py -f -v lab0b
  3. Before moving on to the next step, make sure you identify and correct any and all errors in "lab0b" output. When the check script tells you everything is "ok", you may proceed to the next step.



INVESTIGATION 2: USING THE "IPYTHON" CLI

IPython is an interactive environment that allows us to run python code line by line as we write it. This will also act like a bash shell prompt allowing users to enter a limited number of Bash shell commands. You will notice this by seeing an [IN] prompt where to enter commands and an [OUT] prompt that will display output from issued commands. We will start creating scripts out of the code within this IPython environment.
Important.png
ipython and python
What is the difference between python and ipython? Please note that in later labs, you can use either python or ipythone as the interactive python shell.


PART 1 - Common Ipython Commands and Features

Using Magic Functions

Lets begin by running some python code in the ipython interactive shell. This is a advanced python shell, similar to the bash shell that you have been using throughout the Linux courses. Throughout these labs the term command can also refer to these "magical functions".
Perform the following steps:
  1. Make sure you're using your regular user login and not using the root user for the following section.
  2. To access the ipython shell, issue the following command:
    ipython3
    Now we are now inside the IPython environment. We can run some basic bash commands within this shell by issuing IPython magic functions.
  3. Lets try a few commands out now:
     ls
     pwd
     cd ~/
     ls
    Remember: You are not using Python here, instead, these are aliases for Bash shell commands that IPython gives you access to. What you are actually using is bash, but not all bash commands are available in the IPython environment.

  4. Lets find out which ones are available, type the following command into the IPython shell:
     alias
    We should now have a list of all the bash commands available in IPython.
  5. Lets setup a directory structures for completing and organizing labs. These should be the locations to store your lab scripts.
     mkdir ~/ops435/lab2
     mkdir ~/ops435/lab3
     mkdir ~/ops435/lab4
     mkdir ~/ops435/lab5
     mkdir ~/ops435/lab6
     mkdir ~/ops435/lab7
     mkdir ~/ops435/lab8
  6. If you are interested in finding more information about other magic functions in IPython, then within the IPython shell, and enter the following (press the letter q to exit this function):
     magic
This resource will appear OVERWHELMING (a huge amount of information)! As we move throughout this course, you will slowly use different magic functions from here, but we will never use all of them. They cover a huge range of different tasks, while we are writing code, allowing us to interactively inspect the Python we are writing and running. Lets move on for now.
  1. Issue the following command to exit your ipython session:
     exit
  2. In the future see if ctrl-d works instead of issuing the exit command to quit the ipython shell.
  3. Perform the following steps to evaluate this unit. Run these check scripts regularly as you work through the labs, they may give you hints if you get stuck.
  4. cd ~/ops435/lab1/
    pwd #confirm that you are in the right directory
    ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab0c



INVESTIGATION 3: WRITING PYTHON SCRIPTS

In this investigation we will start writing our very first python scripts. These will be very basic and help us practice syntax and foundation skills, such as: outputting text to the screen, storing data inside objects, and using math operators.
Important.png
Object and Variable
The terms object and variable are used to refer to a data item in computer programming. The term variable are mostly used in 3rd generation programming/scripting languages (e.g. bash) while the term object is preferred in object oriented programming/scripting languages like Python. In the context of Python programming/scripting, When you see the term variable in the lab instructions, it can be replaced by the term object.


PART 1 - Common Introductory Python Functions

Creating the introductory "Hello World" Script

You will learn to create a simple python script in this section. This python script will just print the text "hello world". The "hello world" 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 learn how to run the python script from the bash shell.

Perform the following steps:


  1. 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 in another location. Functions can take arguments, use these arguments in some way, and then usually return a result. The first function we will use is the "print()" functions, it's sole purpose is to output information to the screen.

  2. Add the following line into your source code file:
    print()
    And run it from the command-line:
    python3 ./lab1a.py
    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.

  3. Modify your call to print() to inlcude an argument ('hello world'):
    print('hello world')
    This time we should now see that the python function "print()" has outputted 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 a argument to the print function. These words are important for understanding and talking about different aspects of code.

  4. 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.
Idea.png
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.
  1. 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.
    #!/usr/bin/env python3
    
    # 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). 
    
    # Description: This program will output "hello world" to the screen
    
    print('Hello world')
  2. Another way of running a pythion program is executing it directly, e.g.:
    ./test.py
    Note that the file will need execute permissions even though you ran it just fine earlier. Why is that?
  3. Download the check script and check your work. Enter the following commands from the bash shell.
     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://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
     python3 ./CheckLab1.py -f -v lab1a
  4. 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.

PART 2 - Working with Python Objects

In Python, an 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 variables in this lab. You will learn and use other python 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 to assign a string to an object and how to display contents stored in a string object.
Perform the following steps:
  1. Create a python script (called lab1b.py) and first - start with a few simple things to try:
  2. Let's make a new object containing a value:
    name =  'Thomas'
  3. Print the value to the screen:
    print(name)
  4. Think about why this does something different:
    print('name')
  5. 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 2 strings together. However, make sure that your object is always outside the quotes, or it will not resolve to a value.
    print('I have a friend named ' + name)
  6. 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:
     cd ~/ops435/lab1/
     ./lab1b.py
     How old are you Isaac?
    Try the checking script as you are working through a script to sometimes get hints.

  1. Download and run the checking script. Enter the following commands from the bash shell:
    cd ~/ops435/lab1/
    pwd #confirm that you are in the right directory
    ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1b
  2. 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.

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:
  1. Create a python script (called lab1c.py) and first - start with a few simple things to try:
  2. Lets create some new objects to play with.
    num1 = 5
    num2 = 10
  3. You can print the values in those integer objects:
    print(num1)
    print(num2)
  4. Now we will make a new integer object and try some math:
    sum = num1 + num2
    This will add the values contained in the integer objects together, providing a sum. However you will note that there is no output. Let's inspect the new value:
    print(sum)
    Does this value look right? Are you sure?
  5. Now lets try printing this sum out with a string:
    print('The sum is: ' + sum)
    What happened? Did you receive an error? This will 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.

    In order to use display this number as a string we will use the "str()" function on it. 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 interger object.

  6. Issue the following:
    print('The sum is: ' + str(sum))
    What did you notice this time?
  7. To gain practice, complete your python script with the following features:
  • 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 object should be 72
  • The script, when executed, should print out "Isaac is 72 years old!"
Example run:
cd ~/ops435/lab1/
./lab1c.py
Isaac is 72 years old!

Try the check script as you are working through a script to sometimes get hints.
  1. Download and run the checking script. Enter the following commands from the bash shell:
    cd ~/ops435/lab1/
    pwd #confirm that you are in the right directory
    ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1c
  2. 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.

PART 5 - MATH OPERATORS

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:
  1. Try some of the following to see what happens in Python:
    print(10 + 5)    # addition
    print(10 - 5)    # subtraction
    print(10 * 5)    # multiplication
    print(10 / 5)    # division
    print(10 ** 5)   # exponents
    NOTE: You must be careful when combining more complex math operators together. Python uses PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) to resolve math.

  2. Go over the below examples and see if you understand each situation:
    print(10 + 5 * 2)		# multiplication happens before addition
    print((10 + 5) * 2) 		# parentheses happen before multiplication
    print(10 + 5 * 2 - 10 ** 2)	# first exponents, then multiplication, then addition and subtraction from left-to-right
    print(15 / 3 * 4)		# division and multiplication happen from left-to-right
    print(100 / ((5 + 5) * 2))	# the inner most parentheses are first performing addition, then parentheses again with multiplication, finally the division
  3. 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:
cd ~/ops435/lab1/
./lab1d.py
10 + 2 * 5 = 20
Try the checking script as you are working through a script to sometimes get hints.

  1. Download and run the checking script. Enter the following commands from the bash shell:
    cd ~/ops435/lab1/
    pwd #confirm that you are in the right directory
    ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1d
    Before moving on to the next step make sure you identify any and all errors in "lab1d.py".

  2. When the check script tells you everything is "ok", you may proceed to the next step.



LAB 1 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: ./CheckLab1.py -f -v
Output of: cat lab1a.py lab1b.py lab1c.py lab1d.py
Be able to answer any questions about the lab to show that you understood it!


For sections A & B:
Submit your output and Python scrips via Blackboard instead.

LAB REVIEW

  1. Write the command to change the hostname of your Linux machine to centos7.
  2. What is the purpose of git? How will git be used in our OPS435 course?
  3. Write the command to create an alias for the Linux command vim which will be called vi in your ipython3 session.
  4. Write the absolute pathname for the ipython3 alias configuration file.
  5. Write Python code that when run, will perform the following tasks:
    1. Contain a she-bang line
    2. Display a greetings message to the user
    3. display an empty line (hint: use the special character \n to print the a new-line character)
    4. Display text, "Your current directory is:" (You are NOT required to display quotation marks)
    5. Display the current working directory pathname (using an appropriate command)
    6. Display another empty line
  6. How do you execute a Python script when you are within the ipython3 shell?
  7. How do you execute a Python script when you are in the Bash Shell (i.e. NOT within the Ipython3 shell)?
  8. Write the pipeline command to check if the CheckLab1.py checking script exists, and download it from the location:
    https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py