OPS445 Lab 1: Difference between revisions

From Littlesvr Wiki
Jump to navigation Jump to search
(Created page with "= LAB OBJECTIVES = :In advance of this lab, you will install a current distribution of Linux to be used as a host machine. You will NOT be required to setup Virtual Machines for this lab (that will be covered in a future lab). 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 addition...")
 
 
(20 intermediate revisions by the same user not shown)
Line 1: Line 1:
= LAB OBJECTIVES =
In this lab we will start writing python programs. 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.


:In advance of this lab, you will install a current distribution of Linux to be used as a host machine. You will NOT be required to setup Virtual Machines for this lab (that will be covered in a future lab). 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.
The tasks in this lab appear to be overly simple because I'm assuming you don't have any programming experience and I need to spend a lot of time explaining basic concepts.


: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 variables''', and performing '''math operations'''.
= Creating your "Hello World" program =
<br><br>


= INVESTIGATION 1: INSTALLING LINUX VM=
You will learn to create a simple python program in this section. This python program 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 program in the python3 shell as well as learn how to run the python program from the bash shell.


=== PART 1 - Installing Your Linux Distribution ===
* Create a new python file in your '''~/ops435/lab1''' directory. Call it '''lab1a.py'''


<!-- Try to use tables and simplify the layers of WIKI to make top links less verbose to students -->
The first Python code we will write is going to call the built-in Python print() function. A function is code that has been defined in another location. Later in the course we will create our own function.
:Centos 7 - release 1161 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.
Functions can take arguments, use these arguments in some way, and then usually return a result. The print() function's sole purpose is to output information to the screen.


: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.
* Add the following line into your source code file:<syntaxhighlight lang="python">
print()
</syntaxhighlight>


* Run your program from the command-line: <syntaxhighlight lang="bash">python3 ./lab1a.py</syntaxhighlight>


:'''<u>Centos 7 VM Details / Minimum Requirements:</u>'''
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.


::*'''Name:''' centos7
* Modify your call to print() to inlcude an argument ('hello world'):<syntaxhighlight lang="python">
::*'''Boot media / Installation:''' CentOS7 Full Install DVD
print('hello world')
:::*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-1708.iso
</syntaxhighlight>
:::*Download outside Seneca College: http://mirror.csclub.uwaterloo.ca/centos/7/isos/x86_64/CentOS-7-x86_64-Everything-1708.iso
::*'''Disk space:''' 50GB
::*'''CPUs:''' 4
::*'''Internal Memory:''' 8GB
 
<!--==== Environment Setup ====


* yum update
This time the python function "print()" has outputted to the screen the words 'hello world'. In a programming lanuages a bunch of characters grouped together 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.
* yum install epel-release # Install extra packages for enterprise linux
* 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
* (optional) yum install screen tmux && ln -s /usr/bin/true /etc/sysconfig/bash-prompt-screen
* hostnamectl set-hostname centos7 # Set your hostname to distribution-name
* yum install python-pip # Install python2.7 pip
* curl -O https://bootstrap.pypa.io/get-pip.py # Download python3.4 pip installer
* sudo /usr/bin/python3.4 get-pip.py # Install python3.4 pip
* yum install python-ipython # Install ipython for python2.7
* pip3.4 install ipython  # Install ipython for python3.4
* dnf install git screen tmux vim
-->


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


:'''Perform the following steps:'''
{{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.}}


:#Regardless of the Linux distribution that is used for this course, these lab will be using and referring to the current version of '''Centos7''' (Graphical Desktop) for our main Linux machine. When creating your VM, refer to the '''Details / Minimum Requirements''' section above for assistance.
You can execute python programs from the command-line without using the '''python3''' program.  
:#Install Centos7 VM selecting the default partitions. When you have finished the installation of Centos7, you may proceed to the next step.
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Unit Evaluation Scripts|Each '''Part''' (within an 'Investigation) is referred to as a '''Unit'''. Each Unit will require that the student download and run a '''Unit Evaluation 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 evaluation 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>


<!--<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 evaluation script:<br><source lang="bash">
* Give your program execute permissions first:<syntaxhighlight lang="bash">chmod a+x lab1a.py</syntaxhighlight>
mkdir -p ~/ops435/lab1/
* And try to run it:<syntaxhighlight lang="bash">./lab1a.py</syntaxhighlight>
cd ~/ops435/lab1/
pwd  #  <-- i.e. confirm that you are in the correct directory
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
python3 ./CheckLab1.py -f -v lab0a
</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>-->


=== PART 2 - Setting up Your Python Environment For Labs ===
You will get some bizarre error messages. The problem is that your program is not a binary (like /bin/ls), it's a script. And a script needs to be executed by an interpreter program.


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.
Since you're running your script in bash, and you haven't told bash otherwise: bash assumes your script is a bash script and tries to execute it as such. That's why you're getting the weird errors.


* Add a shebang line at the top, to tell bash that this is meant to be executed by python3:<syntaxhighlight lang="python">
#!/usr/bin/env python3


:'''Perform the following steps:'''
print('hello world')
 
</syntaxhighlight>
:#The first step is to update your entire system. <source lang="bash">
yum update
</source>
:#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>
:#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>


::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.  
* Run your program again, this time it should work:<syntaxhighlight lang="bash">./lab1a.py</syntaxhighlight>
::Below is a listing of several common text editors and their features.
* Download the check script and check your work. <syntaxhighlight lang="bash">cd ~/ops435/lab1/
<blockquote style="margin-left:35px;">{{Admon/tip|style="padding-left:25px"|Selecting an Appropriate Text Editor|
pwd # Confirm that you are in the right directory
'''Geany''' (recommended text editor for labs)<br>A simple graphical text editor for developers. It is available in the CentOS package repositories.<br>
ls lab1a.py # Confirm that you have the lab1a.py script in your directory
'''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>
ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
'''Sublime'''<br>Another powerful and popular text editor designed for programming. Is not free or open source.}}</blockquote>
python3 ./CheckLab1.py -f -v lab1a
</syntaxhighlight>


<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">
* Before moving on to the next part of the lab: make sure you identify any and all errors in "lab1a.py". When the check script tells you everything is "ok", you may proceed.
yum install python-pip # Install python2.7 pip
yum install python34-pip # Install python3.4 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>


<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>
= Values and Variables =


<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">
In Python, a variable 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''' data types in this lab.
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;">Issue the following commands in your shell to check your work for this section:<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 lab0a
python3 ./CheckLab1.py -f -v lab0b
</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>


= INVESTIGATION 2: USING THE "IPYTHON" CLI =
Different data types are stored in memory in a different way, and the programming language treats them differently. That's true even for some values which seem identical to a human being.


:'''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.
== Strings ==


=== PART 1 - Common Ipython Commands and Features ===
String values contain text to be used in your program. Examples of strings could be user-names, full-names, item descriptions, etc.


==== Using Magic Functions ====
We will now assign a string to a variable and display the contents stored in that variable.


: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".
* Create a python program (called lab1b.py) with the following contents:<syntaxhighlight lang="python">
personName = "Andrew"
</syntaxhighlight>


:'''Perform the following steps:'''
There is a number of important things to understand in that simple line of code:


:#Make sure you're not using the root user for the following section.
# '''personName''' is the name of a variable. It can contain any value you assign to it. Or no value at all.
:#To access the '''ipython''' shell, issue the following command:<source>
# '''"Andrew"''' is a string value. Python knows it's a string value because it's in single quotes. In python single and double quotes do the same thing.
ipython3
# The equals sign is used differently in programming compared to how it's used in mathematics. It does not mean that '''personName''' is equal to '''Andrew'''. Rather: it is an instruction to the computer to '''assign''' the '''value''' on the right side of the '''=''' to the '''variable''' on the left side of the '''='''.
</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>
# In a programming language the '''=''' is called an assignment operator. It's an operator which is used to assign on thing to another.
:#Lets try a few commands out now:<source>
ls
pwd
cd ~/
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>
:#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>


:::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.
This is the sort of stuff that programmers understand implicitly, and if it's not completely obvious to you: think long and hard about those points.


<ol><li value="6" style="margin-left:25px;">Issue the following command to exit your ipython session:<source>
* Print the contents of the personName variable to the screen:<syntaxhighlight lang="python">
exit
print(personName)
</source>
</syntaxhighlight>
</li>
* Add this line, and think about why it does something different:<syntaxhighlight lang="python">
:In the future see if '''ctrl-d''' works instead of issuing the exit command to quit the ipython shell.
print("personName")
</li>
</syntaxhighlight>


<li style="margin-left:25px;">
* In Python the '''+''' operator can be used to concatenate two strings (i.e. append the second one to the first one). Try this:<syntaxhighlight lang="python">
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>
print('I have a friend named' + personName)
:<source lang="bash">
</syntaxhighlight>
* The output will look a little weird, fix it. Note that to a computer a space (and a newline, and a tab) is just another character, like the letter "A".
* Why does this do something different?<syntaxhighlight lang="python">
print("I have a friend named " + "personName")
</syntaxhighlight>
* To gain practice, complete your python program with the following:
# The program should have a '''Shebang line''' like you did for your lab1a.py python program
# The program should use a single variable called "personName"
# The value of the "personName" variable should be "John"
# The program, when executed, should print out "How old are you John?"
* Sample run: <syntaxhighlight lang="bash">
cd ~/ops435/lab1/
cd ~/ops435/lab1/
pwd #confirm that you are in the right directory
./lab1b.py
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
How old are you John?
python3 ./CheckLab1.py -f -v lab0c
</syntaxhighlight>
</source>
* Run the checking script:<syntaxhighlight lang="bash">
</ol>
pwd # Confirm that you are in the right directory
<br><br>
ls lab1b.py # Confirm that you have the lab1b.py script in your directory
ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
python3 ./CheckLab1.py -f -v lab1b
</syntaxhighlight>


= INVESTIGATION 3: WRITING PYTHON SCRIPTS =
* 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>


: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 variables, and using math operators.
== Integers ==


=== PART 1 - Common Introductory Python Functions ===
Integers objects are used to store whole numbers (positive or negative, but without anything after the decimal point). Integers can be used for mathematical operations.


====Creating the introductory "Hello World" Script====
* Create a python program called lab1c.py
* Create two variables to play with:<syntaxhighlight lang="python">
num1 = 5
num2 = 10
</syntaxhighlight>


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 ipython3 shell as well as learn how to run the python script from the bash shell.
Note that neither the 5 nor the 10 have quotes around them. That's how Python knows they are numbers and not strings.


:'''Perform the following steps:'''
* You can print the values in those variables:<syntaxhighlight lang="python">
print(num1)
print(num2)
</syntaxhighlight>
* Create a new variable called "sum" and do some math:<syntaxhighlight lang="python">
sum = num1 + num2
</syntaxhighlight>


Again, this is obvious to experienced programmers, but you might want to take some time to consider everything that's happening on that line of code:


:#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>
# The '''value''' is retrieved from the num1 variable.
:#Add the following line into your source code file:<source>
# The '''value''' is retrieved from the num2 variable.
print()
# Those two values are added arythmetically, creating a third value.
</source>And run it from the command-line: <source>python3 ./test.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>
# A '''new variable''' called sum is created.
:# Modify your call to print() to inlcude an argument ('hello world'):<br><source>
# The third value (the sum of the first two values) is '''assigned''' to the variable named sum.
print('hello world')
</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.
<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


# Any line that starts with a "#" is also known as a comment,
Notice that despite all that being done, there is no output. That's because you didn't instruct the computer to output the sum which was calculated.
# 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
* Let's inspect the value inside the sum variable:<syntaxhighlight lang="python">
print(sum)
</syntaxhighlight>


print('Hello world')
{{Admon/tip|Does this value look right? Are you sure?|Your answer should be "no". You might be sure this program does what you think it should, but since I wrote it and I didn't tell you what I intended: you actually can't be sure it's right. The uncertainty comes from the fact that '''5''' and '''10''' are treated as numbers when they are added. But they could have been declared as strings ('''"5"''' and '''"10"'''), and adding them would result in a value of '''"510"'''. Don't be so sure that is the wrong answer, it really depends on what your code is supposed to accomplish.}}
</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?
<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://raw.githubusercontent.com/Seneca-CDOT/ops435/master/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>


=== PART 2 - Working with Variables ===
* Now try printing this sum out with a string:<syntaxhighlight lang="python">
print('The sum is: ' + sum)
</syntaxhighlight>


:A variable 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 variable types in future labs.
This will give you an apparently unwarranted error, but if you disagree with it: you probably don't yet fully understand the reasoning behind having types.


==== String Variables ====
# When you add two strings: they are concatenated.
# When you add two numbers: they are arithmentcally added.
# What's supposed to happen when you add a string and a number?


:String variables 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 a variable and how to display string variables.
Python will not assume on your behalf that the number should be converted to a string and concatenated to the first string, because that might not be what you want. If it is what you want, you have to be explicit about it.


:'''Perform the following steps:'''
* Try this instead:<syntaxhighlight lang="python">
print('The sum is: ' + str(sum))
</syntaxhighlight>


:#Create a python script (called lab1b.py) and first - start with a few simple things to try:
* To gain practice, complete your lab1c.py with the following features:
:#Let's make a new variable containing a value:<source lang="python">
# The program should have a Shebang line.
name =  'Thomas'
# The program should have a variable called '''personName'''
</source>
# The program should have a variable called '''age'''
:#Print the value to the screen:<source lang="python">
# The value of the '''personName''' object should be '''John'''
print(name)
# The variable '''age''' should contain a integer
</source>
# The value of the '''age''' variable should be '''72'''
:#Think about why this does something different:<source lang="python">
# The program, when executed, should print out "John is 72 years old!"
print('name')
* Sample run:<syntaxhighlight lang="bash">
</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 2 strings together. However, make sure that your variable 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 variable called "name"
::::* The value of the "name" variable 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 directory
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
python3 ./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 procede to the next step.</li></ol>
 
==== Integer Variables====
 
:Integer variables are used to store a 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 variable, 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 some new variables to play with.<source lang="python">
num1 = 5
num2 = 10
</source>
:#You can print the values in those variables:<source lang="python">
print(num1)
print(num2)
</source>
:#Now we will make a new variable and try some math:<source lang="python">
sum = num1 + num2
</source>This will add the values contained in the variables together, providing a sum. However you will note that there is no output. Let's inspect the new value:<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 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 variable, your variable is still a interger.<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:
:::* The script should have a Shebang line.
:::* The script should have a variable called '''name'''
:::* The script should have a variable called '''age'''
:::* The value of the '''name''' variable should be '''Isaac'''
:::* The variable '''age''' should contain a integer
:::* The value of the '''age''' variable should be '''72'''
:::* The script, when executed, should print out "Isaac is 72 years old!"
:::Example run: <source>
cd ~/ops435/lab1/
cd ~/ops435/lab1/
./lab1c.py
./lab1c.py
Isaac is 72 years old!
John is 72 years old!
</source><br>Try the check script as you are working through a script to sometimes get hints.<br>
</syntaxhighlight>
<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">
* Download and run the checking script:<syntaxhighlight lang="bash">
cd ~/ops435/lab1/
pwd # Confirm that you are in the right directory
pwd #confirm that you are in the right directory
ls lab1c.py # Confirm that you have the lab1c.py script in your directory
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
python3 ./CheckLab1.py -f -v lab1c
python3 ./CheckLab1.py -f -v lab1c
</source></li>
</syntaxhighlight>
<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 procede to the next step.</li>
* 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.
</ol>


=== PART 5 - MATH OPERATORS ===
=== Arithmetic ===


:In the previous section, you performed a couple of simple mathematical operations. In this section, you will learn some additional mathematical operations.  
The stuff in this section is self-evident, assuming you remember the math you were supposed to have learned in grade 5. But even if you don't: it's unlikely that you'll be doing anything that requires this knowledge.


:'''Perform the following steps:'''
* Try some of the following to see what happens in Python:<syntaxhighlight lang="python">
 
:# Try some of the following to see what happens in Python:<source lang="python">
print(10 + 5)    # addition
print(10 + 5)    # addition
print(10 - 5)    # subtraction
print(10 - 5)    # subtraction
print(10 * 5)    # multiplication
print(10 * 5)    # multiplication
print(10 / 5)    # division
print(10 / 5)    # division
print(10 ** 5)  # exponents
</syntaxhighlight>
</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">
Python decides on the order of operations based on the very common '''PEMDAS''' ('''P'''arentheses, '''E'''xponents, '''M'''ultiplication and '''D'''ivision, '''A'''ddition and '''S'''ubtraction).
print(10 + 5 * 2) # multiplication happens before addition
 
print((10 + 5) * 2) # parentheses happen before multiplication
* For the following examples: try to figure out in your head what the answer should be, and then add that line to your program to check your thinking.<syntaxhighlight lang="python">
print(10 + 5 * 2 - 10 ** 2) # first exponents, then multiplication, then addition and subtraction from left-to-right
print(10 + 5 * 2)         # multiplication happens before addition
print(15 / 3 * 4) # division and multiplication happen from left-to-right
print((10 + 5) * 2)       # parentheses happen before multiplication
print(100 / ((5 + 5) * 2)) # the inner most parentheses are first performing addition, then parentheses again with multiplication, finally the division  
print(15 / 3 * 4)         # division and multiplication happen from left-to-right
</source>
print(100 / ((5 + 5) * 2)) # the inner most parentheses are first performing addition, then parentheses again with multiplication, finally the division  
:#To gain practice, complete your script with the following content and details:
</syntaxhighlight>
::* The script should have a Shebang line.
 
::* The variable '''x''' should contain a integer with the value '''10'''
* To gain practice, complete your lab1d.py with the following:
::* The variable '''y''' should contain a integer with the value '''2'''
# The program should have a Shebang line.
::* The variable '''z''' should contain a integer with the value '''5'''
# The variable '''x''' should contain a integer with the value '''10'''
::* The script, when executed, should print out "10 + 2 * 5 = 20" (the printout should change if the values in the variables change)
# The variable '''y''' should contain a integer with the value '''2'''
:::Example run: <source>
# The variable '''z''' should contain a integer with the value '''5'''
# The program, when executed, should print out '''10 + 2 * 5 = 20''' (the printout should change if the values in the variables change)
* Sample run: <syntaxhighlight lang="bash">
cd ~/ops435/lab1/
cd ~/ops435/lab1/
./lab1d.py
./lab1d.py
10 + 2 * 5 = 20
10 + 2 * 5 = 20
</source>Try the checking script as you are working through a script to sometimes get hints.<br><br>
</syntaxhighlight>
<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/
* Run the checking script:<syntaxhighlight lang="bash">
pwd #confirm that you are in the right directory
pwd # Confirm that you are in the right directory
ls CheckLab1.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab1.py
ls lab1d.py # Confirm that you have the lab1d.py script in your directory
ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
python3 ./CheckLab1.py -f -v lab1d
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>
</syntaxhighlight>
<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'''.]]
 
 
:'''Have Ready to Show Your Instructor:'''
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>./CheckLab1.py -f -v</code>
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>cat lab1a.py lab1b.py lab1c.py lab1d.py</code>


:'''Be able to answer any questions about the lab to show that you understood it!'''
* 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>
<br><br>


= LAB REVIEW =
= Submit evidence of your work =
Run the following command in a terminal:<syntaxhighlight lang="bash">
cd ~/ops435/lab1
python3 ./CheckLab1.py -f
</syntaxhighlight>


:# Write the command to change the hostname of your Linux machine to '''centos7'''.
* The output of the lab check command must say '''OK'''.
:# What is the purpose of '''git'''? How will git be used in our OPS435 course?
* To show that you completed the lab, submit a screenshot of the terminal with that output.
:# Write the command to create an '''alias''' for the Linux command vim which will be called vi in your ipython3 session.
:# Write the absolute pathname for the ipython3 alias configuration file.
:# 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 <u>ipython3</u> shell?
:# 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


[[Category:OPS435-Python]]
[[Category:OPS445]]

Latest revision as of 16:03, 15 January 2025

In this lab we will start writing python programs. 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.

The tasks in this lab appear to be overly simple because I'm assuming you don't have any programming experience and I need to spend a lot of time explaining basic concepts.

Creating your "Hello World" program

You will learn to create a simple python program in this section. This python program 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 program in the python3 shell as well as learn how to run the python program from the bash shell.

  • 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 built-in Python print() function. A function is code that has been defined in another location. Later in the course we will create our own function.

Functions can take arguments, use these arguments in some way, and then usually return a result. The print() function's sole purpose is to output information to the screen.

  • Add the following line into your source code file:
    print()
    
  • Run your program 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.

  • Modify your call to print() to inlcude an argument ('hello world'):
    print('hello world')
    

This time the python function "print()" has outputted to the screen the words 'hello world'. In a programming lanuages a bunch of characters grouped together 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.

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

You can execute python programs from the command-line without using the python3 program.

  • Give your program execute permissions first:
    chmod a+x lab1a.py
    
  • And try to run it:
    ./lab1a.py
    

You will get some bizarre error messages. The problem is that your program is not a binary (like /bin/ls), it's a script. And a script needs to be executed by an interpreter program.

Since you're running your script in bash, and you haven't told bash otherwise: bash assumes your script is a bash script and tries to execute it as such. That's why you're getting the weird errors.

  • Add a shebang line at the top, to tell bash that this is meant to be executed by python3:
    #!/usr/bin/env python3
    
    print('hello world')
    
  • Run your program again, this time it should work:
    ./lab1a.py
    
  • Download the check script and check your work.
    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 http://ops345.ca/ops445/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1a
    
  • Before moving on to the next part of the lab: make sure you identify any and all errors in "lab1a.py". When the check script tells you everything is "ok", you may proceed.

Values and Variables

In Python, a variable 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 data types in this lab.

Different data types are stored in memory in a different way, and the programming language treats them differently. That's true even for some values which seem identical to a human being.

Strings

String values contain text to be used in your program. Examples of strings could be user-names, full-names, item descriptions, etc.

We will now assign a string to a variable and display the contents stored in that variable.

  • Create a python program (called lab1b.py) with the following contents:
    personName = "Andrew"
    

There is a number of important things to understand in that simple line of code:

  1. personName is the name of a variable. It can contain any value you assign to it. Or no value at all.
  2. "Andrew" is a string value. Python knows it's a string value because it's in single quotes. In python single and double quotes do the same thing.
  3. The equals sign is used differently in programming compared to how it's used in mathematics. It does not mean that personName is equal to Andrew. Rather: it is an instruction to the computer to assign the value on the right side of the = to the variable on the left side of the =.
  4. In a programming language the = is called an assignment operator. It's an operator which is used to assign on thing to another.

This is the sort of stuff that programmers understand implicitly, and if it's not completely obvious to you: think long and hard about those points.

  • Print the contents of the personName variable to the screen:
    print(personName)
    
  • Add this line, and think about why it does something different:
    print("personName")
    
  • In Python the + operator can be used to concatenate two strings (i.e. append the second one to the first one). Try this:
    print('I have a friend named' + personName)
    
  • The output will look a little weird, fix it. Note that to a computer a space (and a newline, and a tab) is just another character, like the letter "A".
  • Why does this do something different?
    print("I have a friend named " + "personName")
    
  • To gain practice, complete your python program with the following:
  1. The program should have a Shebang line like you did for your lab1a.py python program
  2. The program should use a single variable called "personName"
  3. The value of the "personName" variable should be "John"
  4. The program, when executed, should print out "How old are you John?"
  • Sample run:
    cd ~/ops435/lab1/
    ./lab1b.py
    How old are you John?
    
  • Run the checking script:
    pwd # Confirm that you are in the right directory
    ls lab1b.py # Confirm that you have the lab1b.py script in your directory
    ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1b
    
  • 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.

Integers

Integers objects are used to store whole numbers (positive or negative, but without anything after the decimal point). Integers can be used for mathematical operations.

  • Create a python program called lab1c.py
  • Create two variables to play with:
    num1 = 5
    num2 = 10
    

Note that neither the 5 nor the 10 have quotes around them. That's how Python knows they are numbers and not strings.

  • You can print the values in those variables:
    print(num1)
    print(num2)
    
  • Create a new variable called "sum" and do some math:
    sum = num1 + num2
    

Again, this is obvious to experienced programmers, but you might want to take some time to consider everything that's happening on that line of code:

  1. The value is retrieved from the num1 variable.
  2. The value is retrieved from the num2 variable.
  3. Those two values are added arythmetically, creating a third value.
  4. A new variable called sum is created.
  5. The third value (the sum of the first two values) is assigned to the variable named sum.

Notice that despite all that being done, there is no output. That's because you didn't instruct the computer to output the sum which was calculated.

  • Let's inspect the value inside the sum variable:
    print(sum)
    
Idea.png
Does this value look right? Are you sure?
Your answer should be "no". You might be sure this program does what you think it should, but since I wrote it and I didn't tell you what I intended: you actually can't be sure it's right. The uncertainty comes from the fact that 5 and 10 are treated as numbers when they are added. But they could have been declared as strings ("5" and "10"), and adding them would result in a value of "510". Don't be so sure that is the wrong answer, it really depends on what your code is supposed to accomplish.
  • Now try printing this sum out with a string:
    print('The sum is: ' + sum)
    

This will give you an apparently unwarranted error, but if you disagree with it: you probably don't yet fully understand the reasoning behind having types.

  1. When you add two strings: they are concatenated.
  2. When you add two numbers: they are arithmentcally added.
  3. What's supposed to happen when you add a string and a number?

Python will not assume on your behalf that the number should be converted to a string and concatenated to the first string, because that might not be what you want. If it is what you want, you have to be explicit about it.

  • Try this instead:
    print('The sum is: ' + str(sum))
    
  • To gain practice, complete your lab1c.py with the following features:
  1. The program should have a Shebang line.
  2. The program should have a variable called personName
  3. The program should have a variable called age
  4. The value of the personName object should be John
  5. The variable age should contain a integer
  6. The value of the age variable should be 72
  7. The program, when executed, should print out "John is 72 years old!"
  • Sample run:
    cd ~/ops435/lab1/
    ./lab1c.py
    John is 72 years old!
    
  • Download and run the checking script:
    pwd # Confirm that you are in the right directory
    ls lab1c.py # Confirm that you have the lab1c.py script in your directory
    ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1c
    
  • 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.

Arithmetic

The stuff in this section is self-evident, assuming you remember the math you were supposed to have learned in grade 5. But even if you don't: it's unlikely that you'll be doing anything that requires this knowledge.

  • 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
    

Python decides on the order of operations based on the very common PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction).

  • For the following examples: try to figure out in your head what the answer should be, and then add that line to your program to check your thinking.
    print(10 + 5 * 2)          # multiplication happens before addition
    print((10 + 5) * 2)        # parentheses happen before multiplication
    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
    
  • To gain practice, complete your lab1d.py with the following:
  1. The program should have a Shebang line.
  2. The variable x should contain a integer with the value 10
  3. The variable y should contain a integer with the value 2
  4. The variable z should contain a integer with the value 5
  5. The program, when executed, should print out 10 + 2 * 5 = 20 (the printout should change if the values in the variables change)
  • Sample run:
    cd ~/ops435/lab1/
    ./lab1d.py
    10 + 2 * 5 = 20
    
  • Run the checking script:
    pwd # Confirm that you are in the right directory
    ls lab1d.py # Confirm that you have the lab1d.py script in your directory
    ls CheckLab1.py || wget http://ops345.ca/ops445/CheckLab1.py
    python3 ./CheckLab1.py -f -v lab1d
    
  • 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.

Submit evidence of your work

Run the following command in a terminal:

cd ~/ops435/lab1
python3 ./CheckLab1.py -f
  • The output of the lab check command must say OK.
  • To show that you completed the lab, submit a screenshot of the terminal with that output.