## The EPIC Lab

Hey folks,

Since 1D04 is weighted higher than your other courses, it is important to achieve a good grade. Some students are struggling with the major lab content, and all students could use a little extra help and bonus marks.

The McMaster Epic Lab provides opportunities for students to work hands-on with some pretty sweet technology, learning about Python and seeing their work come to life in a variety of projects. For every lab you complete, you also get a 1% bonus on your final grade. Students that do all four Epic labs can get up to 4%. That’s almost a full grade point!

### Makeup Lab Sessions

Makeup labs are available for students whose timetable conflicts with the normal EPIC time slots. There will be one makeup lab session for each of the EPIC labs (starting with Android Tablets). Please note that only required courses for engineering 1 will be considered a valid conflict, and all students attending a makeup lab session must have previously contacted Jamie for approval. Any students attending or registering for the lab without previously contacting Jamie will not be permitted to participate in the makeup lab session. Additionally, the makeup labs are scheduled on a first come, first served basis; so please consider all conflicts in advance.

### How to Sign-Up for a time slot

• Follow one of the links below to a project you’d like to do.
• To create an account you will require a valid McMaster email. (students will be required to confirm this through a link sent to their email address)
• You will then be presented with a detailed schedule view
• A confirmation e-mail will be sent for any bookings you make.
• If you can’t make a lab that you have scheduled, please delete your booking or contact me.

NOTE:

• Each student can only have one booking per project (This means you can only sign up once for the three weeks this project runs!)
• You cannot change or delete your appointment less than 12 hours before the scheduled lab time
• You cannot add a booking more than three weeks in advance
• There is space for 24 students per time slot, and you will be working in groups of three. If you wish to work with your friends, please ensure you all sign up for the same time slot.

### The Projects

##### Android Tablets   [Sept 11th - Oct 1st]

In this project, you will be using Python to write two apps for Android tablets. Programming is done directly on the tablet. You will:

• Utilize an API
##### Scribbler Robots   [Oct 2nd - Oct 22nd]

In this project, you will be programming a small robot to complete several tasks, such as:

• Drawing shapes
• Exploring the environment
• Processing images from a camera
• Detect Objects

##### Fischertechnik Kits   [Oct 23rd - Oct 14th]

In this project, you’ll be programming an industrial automation robot. You will:

• Detect color
• Sort blocks based on color
• ## First Year Gear

Hey folks, I’ve noticed that textbooks and other gear (iClickers, calculators, etc.) are the subject of many questions. I’ve written a quick guide on how to make sure you’ve got everything you need without burning a McMaster sized hole in your wallet.

### 1   Textbooks

Textbooks are an important part of first year, and also a very expensive part. Since there are ~1000 first year engineering students, textbooks are necessary to ensure everyone has an understanding of (or at least the resources to understand) the curriculum. That being said, not all students need to purchase textbooks from the campus bookstore. In fact, I recommend that you do not. According to Titles, the McMaster on-campus bookstore, the publisher receives about 80% of the cost. The rest of the cost is quotes as operation costs, and student services. See the fancy pie graph for a less numerical explanation. Though I believe the dollar amount received by the publisher might be a little high, it doesn’t really matter. A lot of books are available directly from the publisher, so this should theoretically save you at least 20%. There are a lot of ways that you can save time and money getting your textbooks. It is also probably good to note that you do not need textbooks the first day of class. In fact, most students I talk to find they don’t need the textbooks until several classes (sometimes even two weeks) in. Don’t be in a hurry to buy the books, unless you’re planning on getting ahead!

There are many different buying options than the on-campus bookstore. In fact, one of the reasons textbooks are so expensive is because students continue to purchase the books from the campus store at such a high price. The most common alternatives are buying online, buying used, and buying at the Book Swap. There are also legends of easy-to-find digital copies of every first year textbook, but I can’t be sure.

As I mentioned before, the McMaster bookstore known as Titles will have everything you need. However, in the first few weeks, the campus bookstore will have a line of over one hundred students trying to get their textbooks. This can result in hours of waiting to even get into the store. In the latter part of the rush, the store is often out of stock on common items like iClickers, forcing students to leave without having everything they need. In first year, when you’re busy with class and everything else, this can be a major inconvenience. If you plan on buying textbooks from the store, be aware of this and make the time.

Online textbooks will often be cheaper, and can be purchased new or used. One of the most common ways to buy textbooks is through Amazon. Amazon offers a huge selections of textbooks and gives a good description of the book’s edition and condition. Additionally, McMaster students are eligible to receive six months of Amazon Prime. Activate this before you buy your textbooks, and you won’t have to pay for shipping (on Prime eligible books). If you’re looking to activate Prime, you can help me out by using my affiliate link to sign up. Some books I’ve found on Amazon can be as low as 20% the price of buying from the bookstore. Even if you don’t buy online, I recommend at least checking it out so you can see how low textbooks can be priced.

Throughout the year, there are always offers and ways to find textbooks around campus. There are several Facebook groups dedicated to the sale of used textbooks, and there’s almost always someone looking to sell first year engineering textbooks, if you’re willing to go looking. If you’re buying used, I highly recommend the Book Swap.

#### The Book Swap

The Book Swap is probably the best way for you to get your first year engineering textbooks. “Why is this at the bottom then, Jamie?” Because even though I think this is the best method, you should always know all your options first. The Book Swap is hosted every term, and encourages upper-year students to come sell their books to those who need it. A great place to get everything you need, but there will always be a limited quantity, and is subject to participation. More information about the Book Swap will be available by the time you need it!

### 2   Equipment

There is some equipment you will need for first year. This includes (but is not limited to) an iClicker, calculator, lab coat, and goggles. All of this equipment is available new and used as well. It is important to note that you will need everything listed above. Do not enter a lab without the proper equipment, and do not bring an unauthorized calculator to a test or exam.

#### The iClicker Problem

Almost every year, Titles runs out of iClickers. When this happens, students are unable to participate in “mandatory” in-class quizzes and participatory elements of some classes. Don’t worry. Professors understand this situation are accommodate those who are unable to receive an iClicker. If you are one of the students who has an iClicker, do not share it with other students, as this is treated as academic dishonesty. In time, Titles will receive more units, and all students will be able to participate in these quizzes.

#### Calculators

The official McMaster calculator is the Casio FX 991. There are several versions of these, but I recommend the MS, as it is technically the calculator quoted by McMaster (or at least, it was in my first year). Other versions of the FX 991 are allowed, and I’ve never seen a student have any problems with their calculator so long as it says FX 991 on it.

## Surviving Eng 1

So I’ve had a few people express interest in a “how to survive engineering 1″ tutorial. Here it goes! Keep in mind that all of these tips are just an opinion, and they should – as any other advice you receive – be taken lightly. I’ll start with some more common questions, and will include some personal advice I have found to be useful in my time as a student and as a developing professional. I’m going to continue updating this based on student feedback, so please let me know if I’ve missed anything!

### 1.   Picking Courses

For most first years, there will be choices to make when it comes to scheduling and electives. There are really only two things that I think are vital to your success. The first is to avoid 8:30am classes as much as possible. It doesn’t matter if you’re a “morning person”. Trust me. That being said, if you do end up with 8:30am classes (which you likely will), you should go. The second is to ignore all advice on which electives you should take. Don’t look for bird courses, and don’t look for courses that a friend of a friend said was good. Read about the electives, and take them based on your interest. You will succeed in things that you are passionate about. Be aware of the affect a course can have on your opportunities, such as first year economics being a good idea for anyone wanting to get into Engineering and Management.

Make sure you’re taking all the courses you need! Check out the list below for Engineering 1 required courses, and see what your timetable is going to look like. (Please disable Adblock. Support McMaster’s developers)

Required Courses for Engineering I

### 2.   Get Involved (But Know Your Limits)

Reach out to other people. Join a club, pick up a hobby, or get involved with a charity, NGO, or student group. These all allow you to develop as an individual, while giving you a break from your normal routine. That being said, many students can commit too much. This both can affect your studies, and can end up being a cause of stress. If you find yourself in this position, don’t be afraid to back out. Your success comes first.

Edit: (Thanks, Marko Maric)
It is important to note that some clubs and on-campus groups require minimal commitment. These are more casual clubs and can be joined easily, requiring minimal commitment. There are some clubs that require regular participation (weekly, twice weekly, and even daily). These clubs are much more involved, and some require this participation to maintain membership. Be careful when selecting a club, and make sure you’re aware of how much time you will need to put in. The more serious clubs are generally for those who really want to submit their time to the practice.

### 3.   The Hardware

This is slightly out of place, but I have a lot of students ask about what computer they should purchase for university. Here’s my two cents. (Disclaimer: I am a developer and a Mac OSX user)

#### Laptop or Desktop?

Laptop. Mobility is more important than power.

#### PC or Mac?

Here’s where things get a little more complicated, and I recommend you look a little further than first year before making up your mind. PCs are powerful and low-cost, but are generally known to have a wider range of issues, since there are hundreds of hardware manufacturers and purchase options for machines running Windows. Macs are more expensive, but are better for some programs, due to the fact that they operate in a Unix environment. Due to the size of my explanation, I have included further details at the end of this post.

#### Brand

Brand matters. Here’s a list of the brands that I trust and avoid. Please remember that this is just my opinion, based only on personal experience.

Avoid: Acer, HP, Sony, Dell, LG, Alienware
Trust: Apple, Samsung, ASUS, Lenovo

### 4.   Eat, Sleep Repeat

Seriously. If there is one piece of advice that really matters, it’s this. Eating and sleeping are incredibly important [1]. All-nighters will happen, and food will be scarce at 4am while living on residence, but always make sure you prepare ahead for both. I had several friends in first year that failed to maintain a healthy sleep and eating schedule, and all suffered academically as a result.

### 5.   Work Together

Do not confuse this with “share answers” or “sit at a library and pretend you’re all working”. Find people that you connect with, and work with ones that encourage you to do better. Look for people with different skills than you, and learn from each other. Class will not teach you everything you need to know, especially at 8:30am. Therefore, keep yourself surrounded by people with similar work habits (or better). This will not just help you in first year. This will help you forever.

### 6.   Learn Conflict Resolution Skills

In the real professional world, there is no room for ego. You will be faced with many different types of people, and you will not always get along so easily with them. There are many ways to get around this, and to allow yourself to work with people that you otherwise would not get along with. It may sound weird now, but I promise you will benefit from it for the rest of your life. Too often I see new students struggling to work with each other, their professors, and their administrators. Don’t let this get in the way of your learning.

If you want to succeed, you will not be able to do it alone. It is crucial that you are aware of resources available to you and reach out to them whenever necessary. Here’s a list I’ve compiled of student resources. There are many more available, and if you think one should be listed, just contact me!

McMaster Student Success Centre (lots of resources here)

#### Student Physical/Mental Health

Peer Support Line (Confidential phone line run by trained student volunteers)
McMaster Wellness Centre
McMaster PULSE Fitness Centre (on-campus gym, very cheap and convenient)
Recommendation: Learn Meditation

#### International Students

English Language Support

#### Students With Disabilities

IMPORTANT: Register with the SAS

### Continued: Mac vs. PC

In my opinion, PCs are most useful for those going into Mechanical engineering, as CAD software (like the one you will use in first year) is seldom available on Unix machines. I have also heard they are more common in Chemical, Materials, and Engineering Physics, thought I have very little experience with these departments. PCs are upgradable, which is especially useful if you intend to have a computer for more than three years, but the upgradability of some newer PCs tends to suffer due to their small size. If you’re going the PC route, brand matters. It also matters where you buy it. Best Buy is a great place to buy a PC and get a decent warranty on it. Ask about their service plan in store. See below for brand recommendations.

If you plan on going into Software, Mechatronics, Electrical, or CS, I highly recommend a Unix machine. This can either be a Mac, or a PC running (or dual booting) Linux. This is because any development you do should be done inside a Unix environment. PCs simply aren’t meant for development (unless you’re developing in Microsoft’s .NET or otherwise). Macbook’s are always a good Unix option, because they are much easier to become familiar with than Linux, come with a suite of applications for the average user, and have an incredible support system through Apple Care (which I highly recommend on any new purchase). Keep in mind that MacBooks will require a Bootcamp partition or an alternative for first year. For new Linux users, I would recommend Ubuntu or Mint. Both are Debian distros at their core, and will help you become familiar with Linux without sacrificing usability.

### Resources

[1] June J. Pilcher and Allen I. Huffcutt, Effects Of Sleep Deprivation On Performance: A Meta-Analysis, Vol 19 (4) ed. , Journal of Sleep Research & Sleep Medicine, 1996.

## Objects and Classes (Tutorial 11)

### Introduction

Objects can be one of the most difficult programming concepts to understand. Once it clicks, however, it really clicks. I recommend you read and pay close attention to the textbook, and utilize your resources until you understand objects and classes, as your upcoming evaluation will rely heavily on your understanding of these concepts.

Before you begin, please read the Python documentation 9.2. Python Scopes and Namespaces.
This stuff messes a lot of people up during major labs!

Let’s get started.

### A Metaphor

Classes are like a blueprint. They describe the traits and actions of something. Let’s look at a real life example, using a car.

To generalize our example, we will define a car as a vehicle with four wheels and an engine. We know, however, that some cars are different. Some are different colours, or seat more passengers. Our class describes the object in general. For example:

##### Class: Car

The class definition of colour simply states:
The car has a colour.

And for our number of passengers:
The car seats some number of passengers.

Objects are created using the “class” blueprints. So, let’s say we want to build a blue car that seats 5 people. We can then fill in the blanks from our class design to create the object defined as having the colour blue, and room for 5 passengers. We’ll call this car something different than the class name. This is because we want it to be identifiable. We’ll call it MyCar.

##### Formal Definition

To stick with the terms you’ll be required to know, here’s a formal definition of what we just described. Read it slowly and make sure you understand it!

“MyCar” is an object. This object is an instance of the class “Car”. The class defines two attributes, colour, and number of passengers. Both of which can be defined specifically for each instance of “Car”.

### Class Definition

Here’s the basic Python syntax for defining a class:

# Simple class definition
class ClassName:
<statement 1>
.
.
.
<statement N>


There are a few different types of statements that we will use to create our class. I’m going to try to cover all the “types” of statements, but there are many different applications for these, which I will leave up to you.

##### Defining Attributes

In our car example, we decided that every car needs a colour. This colour can (though it does not have to be) be unique for each instance of “Car”. When we initialize an object with certain data, that is called an Attribute.

An Attribute is a piece of data that describes the object. Since our class definition just gives us a blueprint for the object, we need to define attributes to describe the specific instance of the class in a bit more detail.

Attributes are usually defined when we create the object. This is done using Python’s special initialization function “__init__“. (TWO underscores before and after the word “init”)

The __init__ function is called once when the object is first created and takes a few arguments. One is “self”, which always comes first, and we will discuss later. The other two are the parameters that we will be using to specify colour and the number of passengers that the car holds.

When we save attributes, we want to assign them to “self”. This is because of the way that Python handles objects. We can think of it as the actual object running the code. Therefore, when we give it a colour, it has to think:
“Hey, this is MY colour, I’ll save it for my self.

class Car:
def __init__(self, colour, numOfPassengers):
# This is my colour
self.colour = colour
# This is my numOfPassengers
self.numOfPassengers = numOfPassengers

##### Accessors (Get Methods)

Once we’ve stored attributes, we will often need to get them back from the object. In the Vector example you’ve seen in lab, you need to be able to get the x and y coordinates to really make use of the class. Therefore, you will need to create a method that returns the values you’ll need to work with. We’ll apply this to our Car example, noting that we might need to check the colour of the car, or the number of passengers it seats.

class Car:
def __init__(self, colour, numOfPassengers):
# This is my colour
self.colour = colour
# This is my numOfPassengers
self.numOfPassengers = numOfPassengers

# GET methods
def getColour(self):
return self.colour
def getNumOfPassengers(self):
return self.numOfPassengers


Now how do we use these functions? The syntax for Objects and their methods is extremely important. Please make sure you understand this!

In general, the syntax for an object’s instance is:

Object.Method(arguments)


This calls Method from Object’s Class description, and passes it the arguments if necessary. Self is always passed first, and this is done automatically. Do not pass it in, Python will handle that.

##### Defining Functions

Depending on your object class, you will often need it to perform more actions. This can be done by defining additional functions in the same way as we did above. These functions can do anything! They’re just like normal functions, but must still take in “self” in order to operate correctly. The syntax for all functions you will define in an object is:

class Object:
def Function(self, arg1, arg2... argN):
# Do something


“self” is determined when you call the function as follows:

anObject = Object()

#[-self--][method][-arguments--------]
anObject.Function(arg1, arg2... argN)


So if our function does anything to “self”, it is actually performing this action on the instance “anObject”. I’ve decided to go a bit more in depth about the “self” concept. It continues below. All you need to know is how to define object functions, and how to call them properly using Python syntax.

##### The “Self” Concept

No, this isn’t philosophy class. The concept of “self” in object oriented programming is possibly one of the most important concepts to understand. I’m going to do my best to describe it using a few methods and metaphors. Please let me know if it is unclear. Read this next part several times if you need to.

Self is a concept used in Python to describe the “current object”. When you call an object’s method:

myObject.myMethod(argument1, argument2)


You can think of it as instructing myObject to perform the action myMethod using the variables argument1 and argument2. When Python goes to look at the code for myMethod, it goes straight to the Class definition (the blueprint). If we didn’t pass “self”, Python doesn’t know which object we’re talking about. When we use “self”, the identity of myObject is passed, so when Python checks the code for myMethod, it can see myMethod is utilizing some attribute of “self”, and in turn, is utilizing some attribute of “myObject”. An example from the lab follows:

class Vector:
def __init__(self, x, y):
self.x= x
self.y= y


Let’s start here.

Python passes in “self” so that it is in our scope. Otherwise, we would get an error saying it isn’t defined. When we use the statement “self.x = x”, we are saying “the value of x specific to this object is set equal to the parameter passed in”. This is basically a way of saving information inside our objects.

class Vector:
def __init__(self, x, y):
self.x= x
self.y= y
def getX(self):
return self.x
def getY(self):
return self.y


Here, we add two functions to get our X and Y values. Python automatically passes the parameter “self” based on how the function was called. For example:

# Returns the x value from vector 1
# In this case, self is the "vector1" object
vector1.getX()

# Returns the x value from vector 2
# self is the "vector2" object
vector2.getX()


This helps Python determine which value of x we’re returning. Remember that “self” doesn’t come out of nowhere. It is determined outside the class when you’re actually working with the methods of an instance of that class.

If we just told Python to “getX()”, there is no way for Python to know what we want. This will return an error, and this is exactly why we require the specific syntax for calling methods of objects:

Object.Method(args)


Hopefully this clears things up. Your textbook’s chapter on this content is really well done, and I recommend reading it (I know it’s dry, but it’s worth it, I promise!) if you’re still struggling with this understanding. Next major lab will absolutely require you to understand these concepts, so make sure you know them!

## The While Loop (Tutorial 10)

### Introduction

This will be a short tutorial, as while loops are pretty easy. You MUST understand conditionals to continue. While loops rely on a statement to operate. As long as the statement is True, the loop will run. When the statement stops, so does the loop.

### WHILE loop structure

The basic structure of a WHILE loop is as follows:

while (statement):
# Do something


This will execute the code inside the “# Do something” section AS LONG AS the statement evaluates to True. Let’s look at a basic example:

i = 0

while i > 10:
print i
i = i + 1


What will this print? Does the code change if we change the order of the statements inside the loop like so?

i = 0

while i > 10:
i = i + 1
print i


Another way to use a WHILE loop is to utilize the power of IF statements to control the flow of the loop. This is done using a flag. The flag is initially True, and is set to false upon some condition. Once it is false, the WHILE loop stops.

i = 0
flag = True

while flag:
i = i + 1
print i
if i == 10:
flag = False


Check yourself to see how these results are similar.

Yet another way is to set the WHILE loop’s statement to always be True. This would cause the loop to run forever! Fortunately, we can use the break statement to “break out” of the loop.

i = 0

while flag:
i = i + 1
print i
if i == 10:
break


Any of the above methods are suitable for labs. Try to pick the best one based on the problem, and make sure you understand all of them for tests and exams.

### Replacing FOR loops

FOR loops are similar to WHILE loops, but can only operate at a finite length, and can’t natively rely on Boolean operations to control their flow.

As a rule, any FOR loop can be turned into a WHILE loop. However, any WHILE loop can not be turned into a FOR loop.

Try it yourself! Try to turn this FOR loop into a WHILE loop:

for i in range(100):
print "my number is ", i


Easy, right? Now, try to change this loop to a FOR loop.

from random import randint

i = 0
while i != 50:
i = randint(0, 100) #get random int from 0 to 100


Try this out! It’s not possible to change this loop into a FOR loop.

## Conditionals (Tutorial 09)

### Introduction

Loops, functions, and methods have allowed us to deal with a wide range of problems. Usually, these problems have a simple logic flow, which usually involves taking data, performing some action, then outputting the data in some manner (print, write, etc.). Although these skills are important, there are still many problems we are unable to solve.

Digital logic provides a way of thinking that allows us to break complex (often non-numerical) problems into smaller problems, all which evaluate to one of two possible values. The two values are True, and False. These are represented in Boolean data types.

### Type: Boolean

A Boolean is a type in Python, just like a Float or a String is a type. “Bools” or Boolean data are named after George Boole, the logician who prototyped boolean logic.

A Boolean is a type that only has two possible states. The states are True and False. These can also be represented by the digits 1 (True) and 0 (False). For the purposes of this course, we will refer to them as True and False whenever possible.

Let’s define a boolean variable:

myBool   = True
yourBool = False


Remember that the True and False operators in Python must start with a capital letter!

##### Special Cases

- Any Number except zero evaluates to “True”

>>> bool(100)
True
>>> bool(0)
False


- Any String except the empty string evaluates to “True”

>>> bool("Hello")
True
>>> bool("")
False
>>>


- The NULL operator (in Python: “None”) evaluates to False

>>> bool(None)
False


### Boolean Expressions

A boolean expression is a Python expression that evaluates to either True or False. Much like Python’s mathematical operations, which evaluate to mathematical data types such as Int or Float, the Python interpreter calculates them inline.

x = 8*6**(9/12.0)  # This is a mathematical expression. x is type Float.
y = "This is" + " a string." # This is a string expression. y is a String.

z = 1 > 0 #This is a boolean expression. z is a Bool.

# Is "z" True or False?


Boolean statements use operators such as “<", ">“, “and”, “or”, and “==”.

w = 1 > 0
x = 1 < 0
y = (1 > 0) and (1 < 0)
z = (1 > 0) or  (1 < 0)

a = 0 == 1
b = 1 == 1


Try these yourself in the Shell. Do you understand why the values of w, x, y, and z are True or False? When you’re done, take a look at the output:

If it is unclear why these values are returned, let’s break the problem down:

##### Breaking it Down

*Note: Keep in mind that I will use “AND” and “OR” to make my references to these operators clear. However, in Python, the correct syntax is without capital letters (“and”, “or”).

We know it is fact that 1 > 0. Therefore, we expect this value to evaluate to True.
It is true that 1 is greater than 0.

We also know from the same logic that 1 < 0 should be False.
It is false that 1 is less than 0.

That explains the first two examples, w and x. Let’s look further into our values for y and z.

To understand all the operators, let’s use a a few examples.

### The “!=”, “==”, “>”, “<" Operators

These operators are used to evaluate the difference between two variables. They are used just like you would think. The only confusing operator is “==” which compares the equivalence of two values, and is often confused with the “=” operator, which sets a variable equal to some value. Another confusing operator is “!=”, which is True if both elements are not equal.

##### The AND Operator
x and y  # True if both x and y are True


Let’s say your 1P03 group has three members. Member1, Member2, and Member3. You are being graded by a computer that checks if each member is in attendance by using the function memberAttended(member) where member is a group member. This function returns True if the member has attended, and False otherwise.

If all group members must attend a tutorial, you can check if you have succeeded the requirement by checking:

memberAttended(Member1) and memberAttended(Member2) and memberAttended(Member3)


If this evaluates to True (True and True and True), then you pass. Otherwise, it evaluates to false (ex. False and True and True) because Member1 did not attend, you will fail!

##### The OR Operator
x or y   # True if either x or y are True


If only one of your group members must be present to hand in an assignment, you can check if you have succeeded the requirement by checking:

memberAttended(Member1) or memberAttended(Member2) or memberAttended(Member3)

##### AND and OR

Even further, you can check if the assignment was handed in by the function assignmentSubmitted(), and can rearrange the previous example:

(memberAttended(Member1) or memberAttended(Member2) or memberAttended(Member3)) and assignmentSubmitted()
|-------------------------Only one needs to be true---------------------------|     |-Needs to be true--|

The brackets are evaluated just like they are in arithmetic.



### The IF statement

The IF statement is the basic framework for computation based on boolean logic. It executes code based on a boolean statement.

The basic structure for an if statement is as follows:

if (statement):
# Do something


This runs the code in the “Do something” section IF AND ONLY IF the term statement returns “True”. Let’s look at a basic example:

x = 0

if (x == 0):
print "zero"

if (x == 1):
print "one"


What will print? Try running this in IDLE.

ANY Boolean statement can be used in the IF statement. That means as long as (statement) evaluates to True, it will run. Otherwise, it will not. We can use the function bool() to check the Boolean value of something.

##### ELIF

The elif statement is a little different. It can be read as “else, if”. For example:

if (statement1):
# Do something
elif (statement2):
# Do something else


This can be read as “If some statement is true, do something. Else, if some other statement is true, do something else.”

##### ELSE

The else statement is just like elif, but accounts for ALL other cases. It can be read as “else” or “otherwise”. For example:

if (statement1):
# Do something
else:
# Do something else


This can be read as “If some statement is true, do something. Otherwise, do something else.”

This is a great way to “catch” certain interesting cases that variables may have. (Maybe catching a variable to check if it is set to zero before dividing)

I will update this section more. IF statements should be fairly easy, and your textbook has a great section on them. Attempt the practice problems below and let me know if I need to elaborate the
IF statement.

What is the result of the following statement? (Do not use the Shell)

True and True and (False or False or True)
True!We know (False or False or True) is True since one element is True, so:True and True and (True) = True!

What will print from the following code?

x = 5y = 100statement = (x>y) or (y==0)if (statement):    print "one"elif (!statement):    print "two"else:    print "three"if (!statement):    print "four"
twofour

This happens because of the nature of if, elif, and else statements.

First, the program checks if the statement is true. We can see that it is not true, since x is not greater than y, and y is not equal to zero. Therefore, the first IF statement evaluates to False and does not run. The second statement is elif, which only occurs if the IF fails. Since it did, the elif statement will check its statement. The “!” operator inverts the result. Therefore, the statement is now True, and it prints. Since this case is not accounted for, else will never run. We then enter a whole new IF statement, which will evaluate to True, and print “four”.

## Functions (Tutorial 08)

### Introduction

We’ve used Python for an array of applications so far. You should by now be familiar with loops, lists, strings, mathematical operations, and how they all work together. We’ve also used a lot of Python’s built in functions to help us get the job done! Here’s a few examples:

import math

myRange = range(0, 10)
mySqr = math.sqrt(2)
newList = myList.append(newElement)


It’s clear to see how these functions simplify our code. Imagine having to write the range out every time, or to have to create a new list every time you wanted to add a new element! Functions make our lives easier, and help us follow the DRY method discussed briefly in our FOR loop tutorial.

Sometimes, we want to create our own functions. This allows us to simplify complicated parts of code, and allows us to break our program into modules. The importance of modules is also good to know, and I’ll discuss that a bit later.

### Function Definition

So, you want to make a function. Sometimes it can be difficult to think about where to start! In programming, it’s always good to start out with “skeleton code”. This is code that gives us the structure we need, then we can fill it in with more code.

One function you’re already probably familiar with defining is the main() function. This usually contains the bulk of our program, and is defined like this:

def main():
print "Hello World"

main()


We can see how simple this definition is. Let this be our skeleton code.

Breaking it down, we can see the skeleton code has three parts. The first is the declaration. We tell Python that our function’s name is “main”, and that it takes zero arguments, which we can see since the parentheses “( )” are empty.

The second part of the function is the code, or definition. This tells us exactly what the function does. Here, our main() function prints “Hello World” to the Shell.

The last part is our function call. This is when we tell the interpreter that we actually want to run the code inside main. When the interpreter first goes through our code, it notes the definition of main. As it continues down, it sees that we then call on main() to perform its duties. That is why it’s important to always define functions at the top of your code!

### A Simple Function

A simple example of a function would be one that prints a few values to the screen. This is a common task, and is a little bit redundant because Python has the “print” function available. Regardless, let’s use a function to print a String.

def printMyStuff(message):
print message

def main():
printThis = "Hello World"
printMyStuff(printThis)

main()


Run this code in a new document. You can see that the message is printed, but not by our main() function. Instead, our main() function passes some information to another function called printMyStuff, which waits to receive some argument (in this case, “message”) before it runs.

If this is still unclear, picture each function as the member of your 1P03 team. Each member has a duty that must be fulfilled, but requires some information to complete that duty. Thus, each member waits until they receive the data necessary. Then, they process it, and hand it back. This cycle continues until the project is complete and you receive an A.

### More Complex Functions

We’ve seen a simple function above. However, it is usually necessary to create functions that do a little more than just print a message. Let’s do a slightly more complicated example.

Let’s write a function that performs a complex mathematical equation on a number.

def complexMathEquation(number):
result = (number*6371^7)/10000 - number^2 + 1/number - 1
print result

def main():
myNumber = 10
complexMathEquation(myNumber)

main()


You can see how this code could become complicated without the use of functions, especially if we had to use this equation many times.

Let’s try something else!

Create a function that takes a list of numbers as an argument, and prints the sum of those numbers. Remember to create the list of numbers and call your function inside your main(). When you’re done, check it with the code I’ve written below.

Awesome! Let’s learn how to pass values back now.

### Returning

##### Single Returns

In the previous examples, we were only printing from inside our functions. Most often, this is simply not enough. Like in the 1P03 example, information needs to be passed into functions, but also has to be passed back out. Take a look at this common function:

import math
sqrtOfTwo = math.sqrt(2)


Let’s analyze the parts of this code:

math is a library, which contains a bunch of functions we can use.
sqrt() is one of the functions included in math. We access it with the syntax library.function(argument).
two (2) is our argument. In this case, a constant, but it can be a variable as well.
sqrtOfTwo is a variable that stores the result returned by math.sqrt().

When we call the function, it takes the ARGUMENT of 2, and RETURNS our value, which is equal to the square root of two. Returning is very important. We can change the functions above to return values to work with further, or even to send to even more functions.

Let’s look at our example from before:

def listSum(myList):

# Initialize sum
mySum = 0

# Perform summation
for i in range(len(myList)):
mySum = mySum + myList[i]

print mySum

def main():
myList = [1, 5, 10, 25, 100, 4, 88, 21]
listSum(myList)

main()


How can we change this so that the printing can be done inside main()? We need to tell listSum() to return the sum it calculates. In Python, this is easy. We simply use the “return” command. Then, we add a variable in main() that will store the value returned by listSum(). Then, we simply print that new variable, inside main().

def listSum(myList):

mySum = 0
for i in range(len(myList)):
mySum = mySum + myList[i]

# Return our value
return mySum

def main():
myList = [1, 5, 10, 25, 100, 4, 88, 21]
# Call function and save returned value
result = listSum(myList)
print result

main()


You’ll see the results are the same. However, know that the second method is better. Why?

##### Multiple Returns

We can also return more than one value at a time. We do this by separating the values we want to return by a comma, and saving them the same way to our target variables outside the function. This is simple:

def returnTwoNumbers(a, b):
num1 = a - 1
num2 = b - 1

# Return two numbers at the same time
return num1, num2

def main():
a = 5
b = 6

# Save the two returned numbers to n1 and n2
# in the same order they are returned.
n1, n2 = returnTwoNumbers(a, b)

main()


### Modular Programming

Functions can be used if we need to perform some process several times in our program. It can also be used to separate the duty of our code into modules. For example, we may have one function that sets up a list, one that performs our mathematical formula, and one that formats and prints the output. The reason we use three functions for this is simple. If we ever wanted to change the way that we perform the mathematical function, the only code we need to modify is that inside the appropriate function. The rest remains unchanged and works just as expected.

The math library is a sort of module. We can use it without knowing exactly how it works on the inside, and changes can be made to it without our knowledge, so long as the results are still correct.

### Lab Notes

When writing labs that require functions, pay close attention to the lab manual. This will describe what functions you need, and what they are supposed to do. For example, the minor lab last week asked that the graphic window was created inside the GUI function. Many students created it and passed it in as a variable, and would lose marks on a major lab for that. Basically, as always, read the lab!

Secondly, some labs will require you to write a module or library. This basically means that it wants you to write a suite of functions that can be used elsewhere. So, you are to write something similar to (but less complex than) the math library. What this means is that the program does not necessarily have a main() program, and that you MUST NOT run main() at the bottom of your code like we have been doing. Basically, the code you submit should not do anything when run. Just write the functions so that someone else could use them, just like you use the functions from “math”. You can use a main() to test your code, but make sure you remove it before submitting it! Again, read the requirements carefully.

### Practice Problems

Write a function pythagorean() that takes in two variables, A and B, and returns C using the Pythagorean Theorem.

import mathdef pythagorean(A, B):    C = math.sqrt(A**2 + B**2)    return C

Write a function printNtimes() that takes a String S and a number N, then prints S a total of N times.

def printNtimes(S, N):    for i in range(N):        print S

Write two functions:
factorial() takes in a number N and returns the factorial of N.

getResult() must then take the result of the first, and divide it by N^2.
Print the result inside your main() function.

def factorial(N):    ans = 1    for i in range(1, N+1):        ans = ans * i    return ansdef getResult(factorial, N):    ans = factorial/N^2    return ans

## Midterm Preparation

Hey everyone, sorry this is late. I did intend for this to be available closer to the midterm date, but here it goes!

### Things to Remember

No matter how many times I remind students to read the whole problem before answering (see: every lab so far), many people attempt to solve the problem before reading the whole question. You can’t answer a question you don’t understand. Take a breath, read the question, think, then look at the answers if you don’t already know. Do not read half the question, parse the possible answers and pick one you think is right. The questions will try to trick you, so make sure you get all the information out of them.

2. Watch the Time

There are several different types of questions on the midterm. Some take less time than others, and you will be more comfortable with some than with others. Make sure that you do not spend a long time on one question if you’re stuck. Move on and come back to it later if you have time. Speed is your friend, so finish the questions you know first. That will ease your mind, as you’ve already accomplished part of the test, and ensure that you don’t get stuck at the end with no time to finish.

3. Do the Problems

Practice problems are given to you for your own good. Use them! My advice is to scan all lecture and tutorial slides for questions, and answer them on paper as you go. Once you’re done going through all the slides, attempt the practice midterm without looking at the solutions. Once you’re done, throw out your answers and do it again. Only after the second attempt should you check your work with the answers. Trust me on this one. There are also some practice problems some of my tutorials.

4. Write the Code

If you’re stuck on a question that includes segments of code and asks something like “what is the result?” or “are both outputs the same?”, do not refer to the answers. Open IDLE and type the code yourself. Use “print” statements where necessary to see how the code is working, and use that to determine your answer.

If you don’t understand a question, don’t accept failure. Ask your friends, check Google, or even visit the help centre. For the rest of the night, I will be answering specific questions via email as well. Use all your resources. Check PyDocs if you are confused about a data type or a function as well. This documentation is complete and always helpful.

##### Practice Problems

Here’s a small set of practice problems that I think will help you. Attempt all questions before looking at the answers. If you’re still struggling, check out Codecademy. It has great free tutorials on Python and can start from the ground up if you’re really stuck.

Also check out Google’s Python class (navigate using the left sidebar). Note that these lessons may differ from your course material, so be careful!

[tab_item title="Problem 1"]
Define the following terms (write it down!)

• Variable
• Expression
• Statement
• Operator
• String
[/tab_item]
Variable: A reference to reserved memory intended to store some value of any type. It is easy to think of a variable as a labelled jar. This jar can contain any information, but can only store one value at a time (a list still counts as one value). A variable can be any sequence of characters that begins with an underscore or a letter, and is not otherwise reserved by Python.

Expression: Expressions are statements that only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator “()” the subscription operator “[]” and similar, and can be reduced to some kind of “value”, which can be any Python object. Think of it as code with the ability to “express” some value. For example:

3 + 5     #expresses the value 8
myList[0] #expresses the value of the first element in myList
range(y)  #expressest the range from 0 to y-1


Statement: Statements are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. For example:

print 42
for i in range(0, 10)
a = 7  #the assignment statement


Operator: Used to construct Python statements, operators aused to create an expression or statement that is not a function or variablection or variable. These include things like “+”, “-”, “/”, “=”, and even the quotes ‘”‘.

String: A String is a data type which stores any sequence of characters that express “text”. This includes any sentence or word (“Hello”), any single character (“A”), and the empty string (“”). Think of it as “stringing” together several characters.
[/tab_item]

[tab_item title="Problem 2"]
Identify three errors in the following expression without typing it in to IDLE:

math.pi*(myNumber**(1/2))*8cos(pi/2)


Then, correct the code.
[/tab_item]
Errors:
- Integer division
- “cos” and “pi” must be referenced through the math library
- (b)a is not correct. It must be entered as (b)*a

math.pi*(myNumber**(1.0/2.0))*8*math.cos(math.pi/2.0)


[/tab_item]

[tab_item title="Problem 3"]
Enter the following commands into IDLE:

  1 == 1
'1' == '1'
'1' == 1


For now, don’t worry too much about the use of conditionals. Why are the first two true (1 is in fact equal to 1, and “1″ is equal to “1″), but the third statement is not?
[/tab_item]
The third statement checks the equality of the integer 1, and the string “1″. Though the string looks the same, its value is much different. (Why is this? Think about its Unicode value).
[/tab_item]

[tab_item title="Problem 4"]
There is no answer for this question.

Write ten valid Python statements, and ten invalid Python statements. Try your best to be creative, and try some out to see what the Shell gives you. This will help you develop an understanding of what you can and can’t do in Python.
[/tab_item]

## Strings (Tutorial 07)

A lot of students have been struggling with the String type. Your understanding of this type is extremely important, and failure to understand will seriously impact your performance in labs. Therefore, I’ve decided to dedicate a post entirely to the use and manipulation of Strings.

### What is a String?

In programming, a letter, symbol, space, new line, or tab is usually referenced by a numerical value (encoded by ASCII or Unicode). This is called a character, or char. A String is what we use to place several of these characters in sequence to form a word or other expression (ex. “dog”). It is literally a “string” of characters!

In Python, we will use the String type for any combination of letters, even if it is only one character. Strings are identified by placing the value between quotes:

myString = "Hello World."


Strings are usually used to store words that relay information, but they can also be used to store numbers. Note that if a number is defined as a string, you can not perform arithmetic operations properly on it!

Try it yourself! How does Python handle these commands?

>> "2" * "2"
?
>> "5" * 100
?
>> "5" + "9.0"
?
>> "5"**2
?


### Manipulating Strings

Strings are versatile, and they can store many types of information. From single letters, to entire documents of data. Strings are also fairly easy in Python, but they are not mutable. This means you can do this:

myString = "I am a dog"
letter_i = myString[0]


But not this:

myString = "1234567890"
myString[0] = 1


Once a String is made, you can not directly change it. To make changes to a string, you must perform the manipulation and save over the value. For example, to add some text to a string:

myString = "This is some text"
myString = myString + " and this is some more text"
print myString


Notice how we referenced the value of myString, but did not attempt to change it directly. Instead, we made a new string (line 2), and saved over the old value inside myString. If this is still unclear, please let me know or refer to your textbook.

There are a few other ways to manipulate Strings as well. Your textbook outlines these well, and I will touch on them here. I recommend you try these in the Shell to see the results.:

# Add two strings
"I am a string" + "I am also a String"

# Multiply strings
"ha" * 100

# Split a string on whitespace
# Breaks the string into a list of smaller strings
"this is a string".split()

# Split a string on something else
# In this case, split on the period
# Don't forget quotes!
"These are two sentences. We must separate them.".split(".")

# Strip a string ONLY removes the target from the ends of the string
# of the specified character from the left and right.
"_hello world_".strip("_")

# Notice the difference here:
"_hello_world_".strip("_")

# Take a slice of a string.
# Remember this notation is like the range function.
# It includes the lower limit(0), but not the upper limit (4)
myString = "This is a string, but I only want the first word."
myString[0:4] #Includes 0, 1, 2, 3.

# Number of characters in a string (look familiar?)
len("There are 39 characters in this string.")



Remember when a String is in a list, you must access the String as an element in the list before you can perform these operations on it. For example, I have the list of strings:

myStrings = ["a", "b", "c", "d"]


To access these strings, I have to reference them inside the list. If I wanted to add them all together:

myStrings = ["a", "b", "c", "d"]
newString=""
for i in range(len(myStrings))
newString = newString + myStrings[i]


Try this and see what your result is. This method can be very helpful for various problems, including your recent minor lab.

### Minor Lab: Word Count

A lot of students struggled with this lab. Let’s see how we can take a document, and count the lines, words, and characters inside. You will need to know this stuff for your major lab.

Here’s my .txt file:

Here is my document.
I have a few lines,
and some words.
I've added some numbers at the end
after the blank line.

1234567890


Now let’s open the file, and calculate three things:
1. The number of lines in the file
2. The number of words in the file
3. The number of characters in the file (including spaces, but excluding new line characters)

Then we’re going to create a new file, “output.txt”, and print our results to that file.

Remember when I hit enter in Notepad (TextEdit for MacOSX), I created a new line character, which shows up as “\n” in python.

Note: This example requires that we copy a list. You should know from class that there are special methods to copy list A to list B so that changes to B do not affect A. There is a well-written example of this here.

# File: minorLabCounter.py
# Author: Jamie Counsell
#
# This file computes the number of lines,
# words, and characters in a given file.
#
# Note: there are many ways to accomplish this task.
# The one I have chosen is easiest to explain.

# Open and read the file. ONLY DO THIS ONCE.
# Save the data to a variable that you do not change,
# So you always have the data when it's needed
fileName = raw_input("Enter the file name:") #Always returns String
f = open(fileName, 'r')

# Break the file into a list of lines, where each line ends
# with the new line character, except for the last line.
f.close()

# Here's a visual example of why I only need
# to open the file once.
lineCountData = list(fileContents) # Use the list constructor to create
wordCountData = list(fileContents) # a new instance of the list every
charCountData = list(fileContents) # time.

# --------------- LINE COUNT --------------------

# We know we just seperated the data into a list
# of lines, where each line is a single element.
# Therefore, the length of that list is the same as
# the number of lines
lineCount = len(lineCountData)

# --------------- WORD COUNT --------------------

# We already have the lines seperated, but need to futher
# Seperate the words from each other. To do this, we can use the
# split() command. Remember we must split up the words in each
# line inside the list.

# Initialize our sum
wordCount = 0

# Iterate through our entire list (each line)
for i in range(len(wordCountData)):

# Split the line into a list of words.
wordCountData[i] = wordCountData[i].split()

# Update our sum with the number of words in each line
wordCount = wordCount + len(wordCountData[i])

# ------------- CHARACTER COUNT -----------------

# Initizlize our sum
charCount = 0

for i in range(len(charCountData)):
# Strip new line characters from the ends of the line
charCountData[i] = charCountData[i].strip("\n")

# Update our sum with the character count of each line
charCount = charCount + len(charCountData[i])

# -----------------------------------------------

# Now we want to construct the output file.
# The best way to do this is to create a string, and then
# simply write that string to a new file.

outString = "Line Count = " + str(lineCount)
outString = outString + "\nWord Count = " + str(wordCount)
outString = outString + "\nChar Count = " + str(charCount)

# Open output file or create if it doesn't exist.
outFile = open("output.txt", 'w')
# Write
outFile.write(outString)
# Close and save changes
outFile.close()


Or a much simpler version of the solution:

data = open(raw_input("Enter the file name:"), 'r').read()      # Read the file to a string
lines = "Lines: " + str(len(data.split("\n")))                  # lines: len of split on newline
words = "Words: " + str(len(data.split()))                      # words: sum of len of lines split on space
chars = "Chars: " + str(sum(len(x) for x in data.split("\n")))  # chars: sum of chars in each line
open("output.txt", 'w').write("\n".join([lines, words, chars])) # Write data to file


These more complex list comprehensions (as seen in the character count) are an interesting tool in Python. If you’d like to know more about how these work, try the python documents here, or ask me in the lab!

## Extra Project 1: Grade Calculator (Tutorial 06)

By now you’re all pretty familiar with Python. We’ve seen how it can be used as a calculator, how it can handle large sets of information with the help of lists and FOR loops, but there’s still so much more we can do with Python (as well as other languages). You will notice the labs begin to add these elements together, so here’s a little DIY project to follow along and get a hang of everything you’ve learned so far.

I highly recommend you attempt to write the code first. Only refer to my solution code to verify that you are correct.

### Introduction

Keeping track of your grades is important in University. Calculating them by hand can be confusing, and it is easy to make a mistake. We’re going to build a small script that will calculate your average grade based on the courses you enter in a .txt file.

Before you start, you should already be familiar with:
Lists
The FOR loop
Handling Files and File I/O
• String Manipulation

Let’s get started!

### Theory

McMaster uses the 12 point grade scale. That means any grade you receive will be an integer between 0 and 12, inclusive. Your average, however, will often be a float. The formula for calculating our average is:

$\Huge Average = \frac{\sum course Grade \times course Units \textup{ (For each course)}}{total UnitsInTerm}$

Basically, we multiply each grade we receive with the number of units in that course, and then sum them. We take that sum and divide by the total number of units we’ve taken so far. Let’s get started in Python.

### The Code

We are entering our grades through a .txt file. To make sure we are able to get all the information we need, let’s stick to a very strict format. Here’s what my file looks like (Download Here: Right click > “Save link/target as…”). Change the contents as you wish to suit your schedule. The number of courses doesn’t matter, but you must make sure they follow the same format.

DEPARTMENT	Course	Grade

CHEM		1E03	5
ENG 		1D04	10
ENG			1P03	8
ENG 		1C03	9
MATLS		1M03	7
MATH		1ZA3	8
MATH		1ZB3	4
MATH		1ZC3	6
PHYS		1D03	10
PHYS		1E03	7
PSYCH		1X03	11
PSYCH		1XX3	9


Go ahead and open up IDLE. Make a new file by pressing ctrl+n (cmd+n on Mac OSX). Save this file in the same directory as your .txt file from before.

This file is going to do all the calculation and print our results. The instructions to build the file are below. Follow along and try your best to write the code. If you get stuck, try adding a few print statements to see what your variables are doing. If you’re really stuck, refer to my code hidden below each section. When you’re done, you can save the file as a .exe so it will run immediately and search for the grades.txt file in its directory.

Good luck!

##### Step 1: Set up .py File

For good practice, let’s describe the file in comments at the top. Here’s what mine looks like:

# File: gradeCalculator.py
# Author: Jamie Counsell (copyright 2013)
#
# 1D04 Extra Project 1
#
# This program computes the sessional
# average of marks given in a .txt file.
#


##### Step 2: Getting The File

First, we need to open the file, save its contents to a variable to be used later, and close it. Go ahead and code that now. When you’re done, come back and have a look at mine. Remember to use only the read permission ‘r’ to avoid accidentally overwriting or erasing the file. (More on File I/O)

• Open the file using Python’s open(file, mode) function.
• Store the contents to a variable content

Before you continue, verify you’re reading the content correctly by printing your content variable to the Shell.

##### Step 3: Splitting it Up

Next, we have to split the content up so it’s easier to work with. We want to separate programs and course codes from their units and grades. Python has a great String method called split() that can help with this. split(), when given no argument, splits a string into a list by separating the string at whitespace. This includes spaces, tabs, and new lines.

We know that the readlines() function gave us a list of strings, where each string is one line. By splitting up these lines, we will get a list of smaller lists, containing all the elements we need.

Example of split():

string = "Python is the best."
print string.split()


We see the output is:

['Python', 'is', 'the', 'best.']


If we apply this to our lines, we can separate program, course code, and mark into their own elements. This is best done inside a FOR loop of the following format:

for i in range( len(content) ):
content[i] = content[i].split()


This will iterate through each element in content (in this case, each element is one line from our file), splitting it and saving the new value (a list separated by whitespace) back to its original spot.

##### Step 4: Removing Junk

Looking at our example file, we know the first two lines do not contain information we need to process. It is best to get rid of these lines before going any further, as attempting to perform calculations on the empty line could cause an error. Luckily, Python has a string method called pop(x) that removes the value located at index “x” of a list, and shifts all other elements to fill the gap.

To remove the first line, we need to remove the first element of the content list. Then, the second element shifts into its place. We want to remove that second element as well. How can we do this using the pop() method? (Hint: list.pop(3) removes the 4th item in a list. The fifth item then shifts into its place, and so on.)

##### Step 5: The Math

To get the number of units in each course, we will utilize a property of the String type. Recall from studying strings that the string “abcdefg” can be referenced by index, just like a list. We see that:
if x = “abcdefg”
x[0]: a
x[1]: b
and so on. Also recall that we can take a slice of the string, such as x[0:2] which will give us “ab”. Remember, like the range function, this includes the lower limit (0), but not the upper limit (2).

Using these methods, how can we determine the number of units that a course is worth, given the course code (ex. 1D04). We know that McMaster course codes have three sections:

1. The first number indicates level (1D04 -> Level 1)
2. The second two numbers indicate course (1D04 -> Course D0)
3. The last number indicates the weight of the course in units (1D04 -> 4 units)

From this, we can see that we need to pull the last character off the course codes, and turn it into a number for our calculations? What type of number should we use? How do we turn a string into this type of number? (Hint: int(’5′) and float(’5′) return the integer and float values of the number 5. Which one is better?)

Our calculations should also be done in a FOR loop. This loop can iterate through each line, adding up all our grades and all the units of our courses. Remember that the calculation requires:
$\sum course Grade \times course Units \textup{ (For each course)}$
and
$\sum unitsInEachCourse \textup{ (For each course)}$

So it’s best to declare these sums before the loop, such as:

# Initialize our sums
totalCredit = 0
totalUnits  = 0


Where totalUnits is the sum of all course units, and totalCredit is the sum of [grade earned times units] for each course.

Use a loop to access all these numbers and perform the correct mathematical operation on them. When you’re done, remember that your average comes from the sums declared above, and is:

average = totalCredit/totalUnits


Print your average to see if you’re correct! If you get stuck, take a look at my code below. When you finish, check with my code to make sure your average is accurate.

##### Step 6: Printing Our Results

Now let’s print some stuff! I stored my average as “average”. I also know my number of courses is the same as the number of elements in my “content” list (one course per line in my file), and I know the total number of units is stored as the sum “totalUnits”.

##### Final Source Code

You can check out the final code below, or download it here. Make sure you write your own code first, though!