OPS245 Lab 8

From Littlesvr Wiki
Jump to navigation Jump to search

!!!THIS LAB IS NOT READY YET!!!

We only have time in this course for a basic introduction to programming using Python. Anyone who tells you that you can learn a programming language in a couple of days a week over two weeks is either an idiot or is lying to you, or both.

We'll cram as much as we can in the time we have available. That's: basic concepts used in most programming languages, and some practical examples of what you can do once you are ready to go beyond those basics.

Basic programming concepts

Python is a scripting programming language. That means you don't need to compile your programs before you run them. The Python interpreter will read your program and execute it step by step.

You will save your programs into plain text files with the .py extension. Like shell scripts: these can be executed using

  • ./yourprogram.py if the file has execute permission and it has the right #! (shebang) line, or
  • By running python3 yourprogram.py

Here's an empty python program. It doesn't do anything. But make one anyway (call it practice.py) to make sure you know how to run it.

#!/usr/bin/env python3

I use a graphical text editor called Geany in Linux Mint to write code, but you can use any editor you like.

Idea.png
Don't copy-paste
If you intend to learn anything in this lab and remember it: don't copy-paste the code examples, type them yourself. That will help both because you'll remember the things you type better, and because you might make mistakes and will have to start learning to read error messages.

Values and variables

One fundamental concept that's sometimes difficult for beginners is the idea of a variable.

Here's a simple way to think about it: a variable is a container with a name which can hold some value. A value can be a number, a string (text), some other kind of data, and one or more other variables.

When you want to work with your value in a variable: you can get it using the variable name.

In Python you don't need to declare what type of data a variable will store, but there are different types of data. The two most common data types are numbers and strings. To make it clear to Python that something is a string, rather than a variable or a function: you put the string in quotes (either single quotes or double quotes).

This program declares a variable called luckyNumber with the number 1 for its value. And another variable called winnerName with the value "Not Andrew":

#!/usr/bin/env python3

luckyNumber = 1
winnerName = "Not Andrew"

print(luckyNumber)
print(winnerName)

This is useful because you very rarely work with values which you know in advance. Numbers and strings will be obtained by your program while it's running. A good program will perform the same function no matter what values it is using.

You can name your variables nearly anything, as long as the name isn't already used. camelCaseIsAStyleWhichSomePeopleLikeToFollow.

Comments

Except for the shebang line everything that follows a # character is called a comment, and is ignored by the programming language. Comments are used for programmers to remember what the code is supposed to do (which is surprisingly difficult even for the author of a program).

This program is identical to the one above as far as the programming language is concerned:

#!/usr/bin/env python3

luckyNumber = 1 # Declare a variable to store a number
winnerName = "Not Andrew" # Declare a variable to store a string

print(luckyNumber)
print(winnerName)

Operators

There are many operators available in a programming language, and Python is no exception. Here are the most common ones:

Arithmetic operators

  • + (addition)
  • - (subtraction)
  • * (multiplication)
  • / (division)
#!/usr/bin/env python3

luckyNumber = 1
print(luckyNumber)

# Examples of basic operations on hard-coded values:

luckyNumber = 1 + 2
print(luckyNumber)

luckyNumber = 997 - 412
print(luckyNumber)

luckyNumber = 20 * 4
print(luckyNumber)

# Things get complicated with division:
luckyNumber = 5 / 3
print(luckyNumber)

# The above does the same thing as a basic calculator. It gets more
# interesting if you use multiple variables:

numBoys = 12
numGirls = 15
numStudents = numBoys + numGirls
print(numStudents)

# And you can use a variable's value to assign a new value to the 
# same variable (it's an important concept, don't gloss it over):

numFilesFound = 10
print(numFilesFound)

numFilesFound = numFilesFound + 1
# At this point the old value 10 is no longer stored anywhere
print(numFilesFound)

Concatenating strings

The + operator does not "add" strings for obvious reasons. But it does something you would expect: it concatenates the two strings:

#!/usr/bin/env python3

firstNumber = 10
secondNumber = 20
addedNumbers = firstNumber + secondNumber
print(addedNumbers)

greeting = "Hello, my name is "
name = "Andrew"
concatenatedString = greeting + name
print(concatenatedString)

# Just because a string looks like a number doesn't mean that it is.
# For strings the + operator concatenates, it does not do an
# arithmetic addition:
firstString = "10"
secondString = "20"
concatenatedString = firstString + secondString
print(concatenatedString)

Assignment operator

The = sign in all the examples above is not the same as the = in algebra. It's an assignment. You might read it like so: assign the value on the right of the = to the variable on the left of the =.

Roughly speaking after the assignment is complete: the right and left have the same value, but it's important not to get confused if you still remember any of your high school math. It's the same symbol, but it's not used for the same purpose.

There are other assignment operators which we don't need to get into now.

Comparison operators

Almost always in order for a program to make a decision it will use a comparison operator:

#!/usr/bin/env python3

luckyNumber = 27

# Is it greater than 10?
print(luckyNumber > 10)

# Is it less than 50?
print(luckyNumber < 50)

# Is it 30?
print(luckyNumber == 30)

# There are also:
# <= for "Less than or equal to"
# >= for "Greater tan or equal to"
# != for "Not equal"

In this example the result of the comparison is just printed as output. In the next section you'll see a more realistic use of these operators.

Conditionals

Most programs need to make decisions on what to do based on some conditions. The simplest mechanism to make a decision is an if/else

If the condition is true: the code with the extra indentation following the if is executed.

If the condition is not true: the code with the extra indentation following the else is executed.

Anything that follows the if/else will be executed regardless of whether the condition is true.

#!/usr/bin/env python3

maxAge = 24; # hours
fileAge = 12; # hours

if fileAge >= maxAge:
    # Note the indentation
    print("Time to delete the old file")
else:
    print("It's not yet time to delete the file")

print("This part will show up no matter what value is in fileAge")

Loops

Often you need to do the same work for multiple pieces of data. Instead of copy-pasting multiple copies of your code into the program you can use a loop.

The most common loop in Python is a for loop. In many other languages it's called a foreach loop.

The same indentation rules apply here as with the if/else.

#!/usr/bin/env python3

# Here's a new data type: a list.
# This particular list contains strings:
filenames = ["/etc/passwd", "/etc/network/interfaces", "/etc/fstab"]

for filename in filenames:
    print("Do something with " + filename + " here"

print("All done.")

Functions

When your programs become non-trivial: you will not want to have pages and pages of code to have to look through to find a problem or add an improvement.

A function is a block of code which does this when you call it:

  • Receives some data as arguments (this is optional)
  • Does some work
  • Returns some value back to the caller (this is also optional)

To write useful functions you need to have a solid understanding of the basics, so you will not be writing any this semester. But you will be using functions, so let's look at how one is created so that you understand what they are.

Note you've already used a function in most of the examples above: print(). In every example we passed a single argument to this function. We did not write the code that outputs any text onto the terminal: whomever wrote the print() function did that. The print() function does not return any values.

Here's an example of a function that might do something useful:

#!/usr/bin/env python3

# Define a function so that we can reuse this code in mupltiple
# places in our program.
# This function is named file_is_too_big
# It is expecting two argiments: a string with the name of a file,
# and a number spicifying what "too big" means.
# It returns True if the file is too big, an false otherwise.
def file_is_too_big(filename, maxSizeInBytes):
    print("Get information about the file " + filename + " from the filesystem")
    # To make this example simple: we'll just make up the size instead
    # of getting it from the filesystem:
    fileSizeInBytes = 32241;
    if fileSizeInBytes > maxSizeInBytes:
        return True;
    else:
        return False;

# Call the file_is_too_big() function and make a decision 
# based on what it returns.
if file_is_too_big("/var/log/messages", 10000):
    print("Rotate /var/log/messages")

# Do the same for every file in this list:
logFileNames = ["/var/log/syslog", "/var/log/auth", "/var/log/maillog"]

# Go through each filename in the list
for filename in logFileNames:
    # Call the file_is_too_big() function and make a decision 
    # based on what it returns.
    if file_is_too_big(filename, 10000):
        print("Rotate " + filename)

Library functions & modules

Everything else

Programming is a profession. And even if you want to tackle it part-time (for example with the goal of being able to do do DevOps type of work): you will need to start using the programming language to accomplish tasks. You will immediately run into problems, and over time you will have no choice but to learn more and more details of this specifc programming language, and how more general systems work (the Linux kernel, TCP/IP, HTTP, unicode, databases, and so on until the end of time).

While that may sound daunting: I can assure you from personal experience that it's worth doing - both for personal gratification and financially. The more you learn: the more complex are the tasks you can accomplish. So every year you'll get better at it, you'll impress yourself, and others.

Shortcuts don't work for learning programming. Struggle, be stubborn, and good things will happen to you in the long run.

Examples