OPS445 Lab 1: Difference between revisions

From Littlesvr Wiki
Jump to navigation Jump to search
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
= THIS LAB IS NOT READY YET!!!=
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 this lab 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.


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.
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.
Line 7: Line 5:
= Creating your "Hello World" program =
= Creating your "Hello World" program =


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.
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'''
* Create a new python file in your '''~/ops435/lab1''' directory. Call it '''lab1a.py'''
Line 70: Line 68:
We will now assign a string to a variable and display the contents stored in that variable.
We will now assign a string to a variable and display the contents stored in that variable.


* Create a python script (called lab1b.py) with the following contents:<syntaxhighlight lang="python">
* Create a python program (called lab1b.py) with the following contents:<syntaxhighlight lang="python">
personName = "Andrew"
personName = "Andrew"
</syntaxhighlight>
</syntaxhighlight>
Line 97: Line 95:
print("I have a friend named " + "personName")
print("I have a friend named " + "personName")
</syntaxhighlight>
</syntaxhighlight>
* To gain practice, complete your python script with the following:
* To gain practice, complete your python program with the following:
# The script should have a '''Shebang line''' like you did for your lab1a.py python script
# The program should have a '''Shebang line''' like you did for your lab1a.py python program
# The script should use a single variable called "personName"
# The program should use a single variable called "personName"
# The value of the "personName" variable should be "John"
# The value of the "personName" variable should be "John"
# The script, when executed, should print out "How old are you John?"
# The program, when executed, should print out "How old are you John?"
* Sample run: <syntaxhighlight lang="bash">
* Sample run: <syntaxhighlight lang="bash">
cd ~/ops435/lab1/
cd ~/ops435/lab1/
Line 114: Line 112:
</syntaxhighlight>
</syntaxhighlight>


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


== Integers ==
== Integers ==
Line 120: Line 118:
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.
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 script called lab1c.py
* Create a python program called lab1c.py
* Create two variables to play with:<syntaxhighlight lang="python">
* Create two variables to play with:<syntaxhighlight lang="python">
num1 = 5
num1 = 5
Line 169: Line 167:


* To gain practice, complete your lab1c.py with the following features:
* To gain practice, complete your lab1c.py with the following features:
# The script should have a Shebang line.
# The program should have a Shebang line.
# The script should have an object called '''name'''
# The program should have a variable called '''personName'''
# The script should have an object called '''age'''
# The program should have a variable called '''age'''
# The value of the '''name''' object should be '''John'''
# The value of the '''personName''' object should be '''John'''
# The object '''age''' should contain a integer
# The variable '''age''' should contain a integer
# The value of the '''age''' object should be '''72'''
# The value of the '''age''' variable should be '''72'''
# The script, when executed, should print out "Isaac is 72 years old!"
# The program, when executed, should print out "John is 72 years old!"
* Sample run:<syntaxhighlight lang="bash">
* Sample run:<syntaxhighlight lang="bash">
cd ~/ops435/lab1/
cd ~/ops435/lab1/
Line 189: Line 187:
* 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.
* 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 ===
=== 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 object '''x''' should contain a integer with the value '''10'''
* To gain practice, complete your lab1d.py with the following:
::* The object '''y''' should contain a integer with the value '''2'''
# The program should have a Shebang line.
::* The object '''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 objects 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) =
* 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>
[[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'''.]]


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


:'''Have Ready to Show Your Instructor:'''
* 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.
::<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!'''
<br>
:'''For sections A & B:'''
 
::<span style=color:green;font-size:1.5em;">&#x2713;</span> Submit your output and Python scrips via Blackboard instead.
 
= LAB REVIEW =
 
:# Write the command to change the hostname of your Linux machine to '''centos7'''.
:# What is the purpose of '''git'''? How will git be used in our OPS435 course?
:# 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.