Lab 01

Hello World!
Due by 10pm on Tuesday, September 9th

In this lab you will be learning how to use the CS lab machines and create Python programs. At the end of this lab you should be able to:

Note that each portion of the lab will be labeled with how many points its worth, and whether it is an individual or partner exercise. For partner exercises, you can optionally work with a partner. If you choose to work with a partner, one of you should turn in the lab assignment with both of your names listed on top. The partner who does not turn in the assignments should submit a text file named README with the name of their partner in it. If you work with a partner, do NOT just split up the assignments and do half each - I expect you to work on them together and discuss them with each other. I will consider dividing the assignment in half and each doing half to be an honor code violation. Additionally, you will be tested on material from the labs, so not doing all of the assignments is a very bad idea. If you need to find a partner, you can post on Piazza to find one.

A reminder about the Honor Code - While you are encouraged to discuss the labs with each other, you should never copy anyone's code, and no one else should ever have a copy of your code. If you do discuss the lab with someone else, or look up resources online, please write that you did so above the honor code in your assignment. On partner assignments, you may work with a single partner, but no one else. (Again, it is fine to discuss the lab with others, but you should never copy their code directly.)

Part 1 - Unix basics

0 points, individual

To use these labs, you'll need a CS lab account. If you registered for this class before, say, Tuesday, then one is already created for you. If you registered late or haven't registered yet, please talk to the lab instructor or a TA (or go see Chris Mohler in OCTET in King 125.)

Before you login, you will need to get a piece of paper with your username and password from the lab instructor. Make sure you get this!

Logging in

You should see a login screen with a window asking you for your username. This should not be the MS-Windows login screen. If it is asking you to press ctrl-alt-del then you'll need to hit those keys and select restart from the window that appears.

Web browser

Be sure to get grade reports

You should also add a rule into your OCMail so that mail from the grader doesn't go into your Spam folder. (This seems to happen randomly throughout the semester.)

Create a folder for the class

Now you need a place to keep all your fantastic stuff. The following instructions will walk you through the creation of a folder to store your work for this course. Items that start with a '%' and look like this are what you should type (without the '%'). Anything after the '#' are informational comments.

    % cd                 # changes the current directory to your home directory
    % pwd                # prints out the directory (to verify where you are)
    % mkdir cs150        # creates a directory named 'cs150'
    % ls                 # lists the contents of your current directory
    % cd cs150           # changes your current directory to the one you just made
    % pwd                # prints out your current directory

Now you'll create a folder for this week's lab. You'll be doing this for each of your lab assignments.

    % cd                # goes back to your home directory
    % cd cs150          # goes into your class folder
    % mkdir lab01       # creates a folder for this lab
    % cd lab01          # goes into that folder
    % pwd               # should show that you are in that folder

Part 2 - Create your first Python program

helloworld.py: 4 points, individual

Alright, on to the good stuff! You are going to participate in a ritual that has been around since at least 1974, the creation of your first program.

There are six steps involved in creating programs in python (or in any other programming language).

Describe the Problem Before writing a program, you must first decide what your program is meant to do. This may seem obvious, but it is surprising how often this critical step is ignored. You should know what the goal and function of the program is. Generally, the problem description will specify what the inputs to the problem are, and what the desired outputs and behaviour are. Usually this is given to you as part of the lab specification.

For your first program we'll just be creating a program that takes in no inputs, and outputs "Hello, world!" to the screen.

Understand the Problem Try some examples, that is, solve the problem (by hand) for a variety of inputs. For one, this will either confirm or deny that you understand what problem you are trying to solve. Furthermore, by trying examples by hand, you may get ideas for how to approach the solution for the problem.

For this program there isn't much to test because we don't have any input.

Design an Algorithm Once you know what problem you are trying to solve and have a feel for its intricacies, you can begin to think about the steps your program will need to take. This set of steps constitutes an algorithm. For all but the simplest of programs, you should have a fully specified algorithm (in pseudocode, a mixture of code-like English and math) before you even think about programming. Exactly how an algorithm should be specified is something you'll get practice with during the course.

Today we'll just be creating a program that prints "Hello, world!" Therefore our algorithm can be specified quite simply: Print "Hello, world!"

Implement a Design Once an algorithm has been specified, we need to translate those steps into Python source code and save them to a file on the computer. This is done with a text editor. In principle, any simple text editor would suffice, but we'll be using an editor called Komodo Edit (NOT Komodo IDE, which is larger and not free). Komodo Edit is a text editor specifically intended for the creation of Python programs. As such, it has a number of functions that streamline the process of editing code. For example, Komodo Edit color-codes terms and instructions based on their meaning and suggests helpful indentation, both of which make reading programs easier.

Creating a file

You need to create a file in your lab01 folder, as follows. You'll want to append a & at the end to run the program in the background. (This means you can still type in the Terminal window.)

    % komodo helloworld.py &

If this is your first time using Komodo, then there will be an information screen that you can ignore for now (you may want to do some tutorials later, up to you). Find the window with 'helloworld.py' in the top bar, and type in the following python code into the file and save it:


    # helloworld.py
    # Say hello to the world.  My first Python program.
    # 
    # <your name>
    # <today's date>

    print("Hello, World!")


If you type "ls" in your terminal window you should see one file: helloworld.py. "ls" gives you a list of the files in a directory.

    % ls                         # show the files

Test the Program The execution of your program is where you get to see the fruits of your labors. In general, you should try running your program on a variety of inputs -- however, since this program does not take any inputs, you can just run it. If the program does what you intended, congratulations! If not, you may need to either go back to the Implementation phase (if you simply failed to implement your algorithm properly), or back to the Design phase (if your algorithm itself contains a flaw).

Running your Program

You should now use the command "python3":

   
    % python3 helloworld.py         # run the program

The output

    Hello, world!

should appear in the terminal window. If everything went as planned, congratulations! You've just edited and executed your first Python program! If there were any error messages, just go back to editing the file and try to make it look like the example above.

Maintain Even after you have a running program, you should keep on developing it in response to the needs of your users. Although you don't have clients to answer to in this course, it is good to get in the habit of writing code that can be easily maintained, so we will encourage you to think about this step.

A few things to note. There are definitely parts of this program that won't mean much to you. That's OK. As we continue through the course, more and more of the pieces we use will be understood, and we'll have to rely less and less on "black magic." That said, a few pieces of the program aren't too hard to understand:

All text that appears after the hash tag (#) is a comment. Komodo Edit colors comments gray. Comments have no effect when the program is run. They are just notes you can leave for yourself and anyone else who ends up reading your code. Making good use of comments is an important skill that we'll talk more about as the course progresses. A standard convention in programming is to have a comment header at the beginning of any program that states the name of the program, the author, the date, and a brief description of what the program does. All your programs should begin this way.

The next line is a call to the print function. Its function is probably pretty clear; it prints whatever is specified in the parentheses. The text is contained within double quotes, which is Python's way of indicating that the text is a literal string of characters, and should be printed just as written.

You can now experiment with modifications of your program. Try changing the contents of the string that is printed, and making a second copy of the print statement. Just make sure the program works before you hand it in!

Part 3 - Callsign

greetings.py: 4 points, individual
fancy.py: 8 points, partner

This will be the first program in which we get input from the user. Start editing a file greetings.py:

    % komodo greetings.py & 

We will use the following code to get input from the user.

    name = input("Enter your name: ")

This should be somewhat familiar; it's just an assignment statement. The expression on the right hand side is a function invocation that uses a built-in python function (input) to get a string from the user. That is, when the program gets to this statement, it will print the statement in the parentheses and pause for the user to enter something and hit enter. Whatever the user types before hitting the enter key will be returned and now stored in the name variable. After the value is assigned, you should print a greeting with a statement such as

    print("So, we meet again,", name, "!")

Notice that we didn't need to add a space after the comma (the comma after "again"), because Python inserts a space automatically. Of course, it will also automatically insert a space before the exclamation point... but we'll fix that in a bit.

Just to confirm, your greetings.py should look something like this, and when you run it, it should ask the user to enter their name, and then prints "So, we meet again, <their name> !"

Now create a program called fancy.py which prompts the user to enter three strings, one at a time, in the following order: First name, last name, and nickname. It should then print "Welcome back, <first name> "<nickname>" <last name>!" For example, for me, assuming I enter my data correctly, it should print:

    Welcome back, Cynthia "The Pink Panther" Taylor!

Hint: To print a double quote, you can't just put a double quote in your string; Python will think you're saying that that's where the string ends. To get around this, you use what is called an escape sequence. An escape sequence is a pair of characters, the first of which is always a backslash (\). To tell Python you want the double quotes character, you'll use the escape sequence \". For example, the statement

    print("Here we have a double quote: \"  Pretty, ain't it?")
will generate
    Here we have a double quote: "  Pretty, ain't it?

Similarly, you can use \', \\, \t and \n to generate a single quote, a backslash, a tab, and a newline respectively. Note that if the quote is at the end of the sentence, you will end up with two quote marks in a row, which will look kind of funny. So printing

My nickname is "The Destroyer"
will look like
print("My nickname is \"The Destroyer\"")
Think about what it will look like if the entire string consists of one quotation mark.

Also, in case you don't want to have whitespace before and after the nickname (you want those double quotes right up snug against the nickname) you need to tell Python by including sep='' in your print call. Similarly, if you don't want a new line after the print statement, you can add end=''. For example, the statement

    print("no", "white", "space", sep='', end='')
will generate
    nowhitespace
all on one line, and the cursor will be at the end of that line (not on the next one.)

You may have noticed that Komodo has undersquiggled some of your code in red, even though you did everything we asked. The problem is that by default, Komodo assumes you're working with Python 2, which has slightly different syntax. To fix this, use the drop-down menu in the lower right corner of the editor to switch the file type from Python to Python3.



Part 4 - Modify a Program

sum.py: 4 points, individual
factorial.py: 8 points, partner
choose.py: 2 bonus points, individual

Here is a program called sum.py that calculates the sum of the first 4 positive integers.

Program Outline


   # sum.py
   # Computes the sum of the first 4 positive integers
   # 
   

   sum = 0
   for i in range(1,5):
       sum = sum + i
   print("The sum of the first", i, "positive integers is", sum)


   

Sum

Your goal is to modify the program so that it prompts the user for a number n and outputs the sum of the first n positive integers. If you can figure out how to do this directly, by all means, go ahead. If you want a bit more guidance, consider the following suggestions:

Note: You will want to "evaluate" the user input as an integer number because by default, what the user types is considered a string literal. You can do this by using the built-in Python "eval" function eval(expression-you-want-to-evaluate)


   n = eval(input( "Please give me a number: "))
   

Test your progam to make sure it's calculating the correct sums. Try a variety of numbers, such as n=5, 10, 100, as well as other critical values such as n=0, -5, etc. Is the behavior of your program on the latter examples sensical?

Factorial

Now create another program called factorial.py based on sum.py. The factorial program will still get a number n from the user, but now instead of calculating the sum for the first n positive integers, it should compute their product. That is, factorial.py should output n! ("n factorial", where n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1). Recall the steps described in part 1: You should start by coming up with a psuedocode algorithm for factorial before you code anything.

Don't forget to test your program on a variety of values of n.

Bonus

If you feel like you're getting the hang of things and want a little bit more of a challenge, write a program called choose.py that gets two integers from the user (let's call them n and k for now) and computes n choose k. The value n choose k counts the number of ways you can choose k objects from a set of n distinct objects, and can be computed as n! / (k! * (n-k)!).


Part 5 - Time Warp

secondconverter.py: 10 points, partner
README: 2 points, partner

In this problem, we'll think about converting units of time. Suppose we have some number of seconds stored in a variable called sec, which may have a value of 60 or greater. Since we're typically not used to thinking about how long 795 seconds is, we might like to improve readability by formatting the time (sec) into minutes and seconds (m and s) such that s < 60. For example, if sec = 137, then we'd like to compute m = 2 and s = 17, since 137 seconds is the same as 2 minutes and 17 seconds.

Similarly, we might want to do the same with but with hours too. That is, suppose we're given seconds (sec). We'd like to calculate how many hours (h), minutes (m) and seconds (s) are in sec seconds, such that m < 60 and s < 60.


Describe the Problem:
The problem we are trying to solve is as follows.
input: get a non-negative integer sec from the user, representing some number of seconds.
goal: convert sec into its equivalent hours, minutes, and seconds, and output the result to the terminal window.


Understand the Problem:
For example, if the user enters 137, the output should read

	137 seconds is equal to 0 hours, 2 minutes and 17 seconds.
Or if the user enters 3601, the output should read
	3601 seconds is equal to 1 hours, 0 minutes and 1 seconds.

Notice I'm ignoring grammatical issues such as "hours" vs. "hour".


Design an Algorithm:
The program has 3 main steps:

  1. Get the number of seconds from the user, store in a variable named sec.

  2. Calculate the number of hours (h), minutes (m), and seconds (s) that are in sec, where m < 60 and s < 60. The mod, or remainder operator (%), as well as the integer division operator (//) will be particularly useful here. We'll be talking about these operator in class soon, but if you'd like to get started on this section of the lab now, you can either check out Section 3.1 of the text, or read on.

    Integer Division ( // ) and Remainder ( % )


    Consider dividing fourteen by four, i.e. (14/4). We'd normally say we 14/4 equals 3.5. But we could also think in terms of "integer division", where we'd say 14/4 equals 3 with a remainder of 2.

    In Python 14/4 evaluates to 3.5, whereas 14//4 gives the integer component of integer division, and thus evaluates to 3. Similarly 14%4 indicates the remainder component (also known as mod), and gives 2. More generally, x//y evaluates to the number of times y goes wholly into x, and x%y evaluates to what's left over afterwards. These operations turn out to be surprisingly useful, as we'll now see.

    Since this step of the algorithm is a bit more complex than the previous one, we'll break it into three sub-steps, one for each variable that we're calculating.

    1. Set s = sec % 60. To see why, note that s should be the number of extra seconds that aren't used up by whole minutes. That is, s should be whatever remains after we divide sec by 60 to get minutes, which is exactly what sec % 60 means.

    2. Set m = ??? (This part is for you to figure out. Before you start programming.)

    3. Set h = ??? (This part is also for you to figure out. Likewise, before you start programming.)

  3. Print the equivalent number of hours, minutes, and seconds for the user.


Implement a Design:
Create a program called secondconverter.py that implements the design above. If you want you can start with the following code in a file named secondconverter.py, and fill in the necessary code under each corresponding comment.

Program Outline


   # secondconverter.py
   # Translate seconds into a more readable hours, minutes, and seconds.
   # 
   # <your name>
   # <today's date>
   
  
	  
   # Explain on the terminal (via print function) what this program does.
   # Prompt the user to enter a number of seconds, store in a variable.
   # Compute hours, mins, and seconds for this input.
   # Print the results.
         


Test the Program:
Test your program by trying a variety of inputs. You can start with the example below, but you should try others as well, especially numbers that you think could be troublesome.

Sample Output


   Welcome to my Second Converter!

   This program will properly calculate the number of
   minutes and seconds under 60 from a given number of seconds.

   How many seconds have you got? 3601 
   3601 seconds is equal to 1 hours, 0 minutes and 1 seconds.	


Maintain:
Suppose that in ten years the world leaders decide that a minute should have 80 seconds and an hour 80 minutes. What changes would you need to make to your program to make it accurate? Put your answers in a README file (just a text file created with any text editor and saved with the name README) and hand it in electronically with the rest of your submission.


Part 6 - Handin

If you followed the Honor Code in this assignment, insert a paragraph attesting to the fact within your README file.

I affirm that I have adhered to the Honor Code in this assignment.

You now just need to electronically handin all your files. This will make a copy of your files available to the instructor and the graders. If you make any changes after you have handed in your work, we won't see the changes unless you hand them in again. You can handin as many times as you need to. (In fact, it is good practice to handin every time you logoff. This way, there is always an up-to-date copy in the graders' directory, and if anything happens to your files (as sometimes does) you won't lose all of your work.)

    % cd                # changes to your home directory
    % cd cs150          # goes to your cs150 folder
    % handin            # starts the handin program
                            # class is 150
                            # assignment is 1
                            # file/directory is lab01
    % lshand            # should show that you've handed in something

You can also specify the options to handin from the command line:

    % cd ~/cs150        # goes to your cs150 folder
    % handin -c 150 -a 1 lab01

File Checklist

You should have submitted the following files:

Remember that if you are working with a partner for the partner components, one partner will turn in fancy.py, factorial.py, secondconverter.py and README with both partner's names written at the top, and the other partner will turn in a README file with the name of their partner in it. Both partners will turn in their own versions of helloworld.py, greetings.py,sum.py, and (optionally) choose.py.


Part 7 - Lab Access

If you are already registered in the class, your ID card should have swipe access to King. This means that you should be able to get into King at all hours on all days. If you haven't registered yet, or registered late, you should go see Jackie Fortino in King 223, pronto, so that she can get you the right access.

Also, you need a code to get into both of the CS labs (King 201 and King 135). I announce this during the first lab, so if you don't know the code yet you should probably ask me.

That's it! You've completed your first lab. Be sure to logout when you are done (either the red-arrow icon at the bottom of your screen, or System->Logout).



Last Modified: June 8, 2014 - A. Sharp, T. Wexler, B. Kuperman, S. Semsioglu, C. Taylor