1C03 Design and Graphics:
Printing Your Project

gears-3

1C03 printing sessions open soon, and it’s important that students come prepared. Below is a list you can follow to ensure your project is printed properly and on time. Failure to follow these instructions could result in your group having a final product that is unfit to submit!

1   Gear Specifications

Constraints are an important part of this project. All of your gears must agree with the design specifications and fit within the given space constraints. Beyond that, there are additional specifications that will ensure your projects can be printed in time.

  • All gears must have a height (when laying down) less than 6mm. 4 – 5mm is recommended. Unnecessarily thick gears will result in high print times.
  • When designing a hole for the gear’s center, always make it less than your desired size, and drill it later (for example, if I’m going to thread a 2mm axle for the gear, I will design the gear with a 1 – 1.5mm hole.
  • Very small gears may cause issues with threading and are not recommended.
  • Projects have been printed with numbers ranging from 4 to 12 gears. The number of gears needed depends on your ratio, so do not compare with your friends on this. Too many gears will increase your opportunity for error.
  • When in doubt, ask your 1C03 TA’s and IAI’s for help before entering the lab. I will be unable to assist you with design during the printing process.

2   The Printing Process

This process is subject to change, and will be updated accordingly. All students must follow this process to have their 1C03 project printed.

  • Students enter the lab prepared, and have 50 minutes to create a print-ready file for submission.
  • The total estimated time for any print must be no longer than 1.5 hours.
  • Groups submit their print-ready file on a USB stick (not provided).
  • Prints are completed in the order they are submitted.
  • Completed prints are announced via @TheEpicLab.
  • Students have one week to collect their printed parts and USB drive.

3   Book Your Printing Session

Registration will open (or is open) online via Supersaas, our scheduling software. Book your printing session early to secure a spot, and make sure you attend your scheduled spot! A few important notes about bookings:

  • Students must make one booking per group.
  • You must have a valid booking to enter the lab.
  • All students on the waiting list must wait outside the lab until they are instructed to come in.
  • If any groups do not arrive by 10 minutes after the session has started, their spot may be given to a group on the waiting list.
  • Again – book early! The sessions fill up fast and some students may be left without a printed project.

4   Come Prepared

All students have exactly 50 minutes in the EPIC lab to create a file for printing. Students must be sure that this file is correct and error-free, as they will likely not be there to witness the print process. Follow these instructions to ensure your group’s printing is a success.

  • Start early! Many students rush and make mistakes in calculations or somewhere else. Take your time and double check your designs. You may not get a second chance!
  • Bring all parts as separate .stl files. One gear per file only!
  • All parts must be in the STL format. There will not be time to modify files in the lab.
  • Seriously. STL files only.
  • Bring all these .stl files on a USB stick. Do not rely on email, Dropbox, or anything else. This USB stick will be left at the lab until you pick up your parts, so please ensure you do not need the USB key or the files on it.

Maintenance

Dear 1D04 students and other visitors,

I have just finished the process of migrating my website in its entirety to a new server. Any difficulties accessing the site should now be resolved. If you find any site features that do not operate normally, or any dead links, please report them to me immediately. Thank you for your patience!

Jamie Counsell

EPIC Game Challenge

l54958_53

Looking to expand your Python skills? Want to put everything you’ve learned in 1D04 into something you can play and share with friends? Join the EPIC Game Challenge! The Game challenge runs twice a year and gives students the opportunity to create a Python based game to submit for competition. Your IAI’s, TA’s, and other students will attempt to complete these submissions at the end of the term.

Getting Started

Be ready to get creative and get your game on! Making a game in Python can seem intimidating at first but with the skills you already have and some extra research you too can make a fun and interactive game!

A great resource to start off on is PyGame, a library with extensive documentation that makes Python game making easier by laying down a foundation for you to work off. Check out the PyGame website to download the library and learn more!

Note:
PyGame offers a lot of graphic capability which can be intimidating but do not feel like you need to make a game that has complex graphics for it to be good. A text-based game can be just as fun and innovative, and often can be equally or more complex in terms of how the user experiences the game!

Submitting a Game and Deadline

Think you have the next best game? Want to share your game and compete with other students to win the challenge? Submit your entries via email with the subject “Epic Game Challenge” to the EPIC IAI at jamiecounsell@me.com.

Submission deadline is December 1, 2014.
Those from last semester can still submit! If any students are looking for assistance on where to start, you can contact me to arrange a short tutorial.

The EPIC Lab

l54958_53

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.
  • You will be asked to log in, or create a login name if this is your first visit.
  • 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]

android-sidepic

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

  • Learn about webservices
  • Utilize an API

Sign up here!


Scribbler Robots   [Oct 2nd - Oct 22nd]

scribbler-sidepic

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

Sign up here!

Fischertechnik Kits   [Oct 23rd - Nov 14th]

fischer-sidepic

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

  • Detect color
  • Sort blocks based on color
  • Sign up here!

    First Year Gear

    Kindle_Reading

    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, Where do your textbook dollars go?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!

    Know Your Options

    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.

    Buying On Campus

    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.

    Buying Online

    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.

    Buying Used

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

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

    6.   Use Your Resources

    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!

    Academic Assistance

    McMaster Student Success Centre (lots of resources here)
    Visit an Academic Advisor

    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:

    Spoiler Inside: Output SelectShow

    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.

    Spoiler Inside SelectShow

    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