OPS445 Lab 1: Difference between revisions

From Littlesvr Wiki
Jump to navigation Jump to search
Line 245: Line 245:
::<span style=color:green;font-size:1.5em;">&#x2713;</span> Submit your output and Python scrips via Blackboard instead.
::<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'''.
[[Category:OPS435]]
:# 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]]

Revision as of 14:04, 6 January 2025

THIS LAB IS NOT READY YET!!!

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.

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.

  • 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 script (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 script with the following:
  1. The script should have a Shebang line like you did for your lab1a.py python script
  2. The script should use a single variable called "personName"
  3. The value of the "personName" variable should be "John"
  4. The script, 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 script 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 script should have a Shebang line.
  2. The script should have an object called name
  3. The script should have an object called age
  4. The value of the name object should be John
  5. The object age should contain a integer
  6. The value of the age object should be 72
  7. The script, when executed, should print out "Isaac 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 script 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 script, 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.

LAB 1 SIGN-OFF (SHOW INSTRUCTOR)

File:Lab1 signoff.png
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.