CSCI 150: Lab 1

Hello, World!
Due: 10PM on Tuesday, February 7

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:

  • Log into a lab machine
  • Create a directory for a homework assignment
  • Use some basic Unix commands
  • Create some simple python programs, and run them
  • Learn how to get input from the user
  • Submit a lab using our handin program.

The lab is broken up into sections to make things more manageable. Every section indicates how many points it is worth. Be sure to read each section carefully to avoid asking questions that are answered in the lab. With the exception of the first one, most labs are expected to take a while (8-10 hours is typical). Get as far as you can in the scheduled lab time, and try to work steadily on the lab throughout the week. Don't leave it all to the day the lab is due.

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 - Setup and Unix basics

0 points

To use these labs, you'll need a CS lab account. If you registered for this class prior to today, an account should already have been created for you. If you registered late or haven't registered yet, please talk to the lab instructor or a TA.

To log in, you need a username and password. Your user name will typically be your Obie ID (the half of your Oberlin email address before the "at" sign). In rare instances (like if your Obie ID has a number), this might not be your username. Try it anyway, and if it doesn't work, Chris Mohler will be around to help you determine your username. Your initial password will be announced in lab.

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.

  • Enter your username.
  • Enter the default initial password. NOTE: You will not see your password on the screen (you might see *'s instead).
  • If you succeed in logging in, you will get a message indicating that your password has expired (since it was a temporary password). You will now be prompted to create and confirm a new password.
  • If your selected password is not secure enough, you may be asked to choose a new one.
  • Note that you may get an erroneous message claiming you failed to change your password. This message is most likely false -- you should try logging in with your selected password.
  • Now that you've changed your password, you'll be asked to login again. Enter your username, and then the new password you just chose. You should now be logged in! In the future, you will just have to enter your username and password to log in.

Web browser

  • Open a web browser by opening the menu at the top left of the screen, selecting Internet, and picking Firefox or another web browser.
  • The very first time you do this it may take a while as the system needs to set up your user information. Don't try clicking repeatedly, as that will just slow things down further.
  • Go to the CSCI 150 home page and familiarize yourself with the policies and the course schedule.
  • Create a shortcut link by dragging the picture to the left of the URL to your bookmark bar.

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

  • Go to http://ocmail.oberlin.edu/ and log in to your Oberlin email.
  • Do a search for from:gr150@cs.oberlin.edu
  • After you've searched, on the right side of the search box, you should hit the gray downward facing triangle, and then select "Create filter with this search" in the bottom right.
  • Check the box for the line "Never send it to Spam"
  • Click on "Create Filter" in the blue button below, and you should be all set.

Sign up for Piazza

Piazza is a forum for course-related discussions. Here you can ask questions about labs, Python, and the course in general. Questions can be answered collaboratively by both the course staff and your classmates. Answering questions yourself is not only a great way to help your classmates, but also earns you participation credit. You can also use Piazza to search for a partner for lab assignments that allow collaboration.

Create a folder for the class

Now you need a place to keep your coursework. 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. You need a "terminal" where you can type. Click on the Applications Menu (probably at the top left of your screen); the first icon is probably a Terminal Emulator. Click on this and a terminal will open on the screen. There are also several terminal options in the Accessories submenu. Type the following (without the comments or %):

    % 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

As your first assignment, you're going to continue a ritual that has been around since the early 1970's -- starting to explore a programming language by first creating a program that prints the words "Hello world!" to the screen. In this course we'll be learning the Python programming language, and using a program for editing code called Komodo. But before we get to that, let's take a step back and look at the overarching process of developing a program.

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

Specify 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. In CS 150, this will typically be 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 our HelloWorld program, the specification is pretty simple and doesn't depend on input, so there isn't much to understand. But even for marginally more complicated programs, this step becomes critical.

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.

For our first program, the algorithm can be specified quite simply: Print "Hello, world!"

It's worth noting that the three steps we've discussed so far do not involve programming a computer! A common rookie mistake is to jump into code too fast, with minimal understanding of the problem, and even less of an idea how to solve it.

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

If you've been following the lab carefully, you've already created a lab01 folder, and are currently inside that folder in your terminal window. If not, back up and do that. Now type


    % komodo helloworld.py &

                                

and press enter. This tells Komodo to create a new file with the specified name, and opens it. If that file already exists, Komodo simply opens it. The & at the end of the line tells the computer to run the program in the background, which means you can still type in the terminal window. If you forget to do this you can either quit Komodo and try again with the &, or simply open a new terminal window.

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. The command "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. For more complex programs, you should try running your code on a variety of inputs, including the examples you generated to further your understanding of the problem (step 2 of this list.) If the program does what you intended, congratulations! If not, you may need to either go back to the Implementation phase (if you 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 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.

So what is happening in our (admittedly simple) program? All text that appears after the hash tag (#) is a comment. Komodo Edit colors comments gray. Comments are ignored by the computer and thus 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 is to have a comment header at the beginning of any program that states the name of the program, its purpose, the author (you), and the date. All your programs should begin this way.

The only actual instruction is a call to the print function. Its purpose is probably evident; it prints whatever is specified within 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 (as opposed to a variable or instruction).

You can now experiment with your program. Try changing the contents of the string that is printed, and making a second copy of the print statement. Just be sure to revert to the original working version before you hand it in!

Part 3 - Callsign

greetings.py: 4 points

fancy.py: 8 points

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


    % komodo greetings.py & 

                                

Add header comments like in your previous program (name, date, etc.). To get input from the user, the first instruction we'll need is the following:

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 method 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 wait for the user to type something and hit enter. Whatever the user types before hitting the enter key will be returned and stored under the variable name. 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 whitespace delimiter automatically. Of course, it will also automatically insert a space before the exclamation point... but we'll fix that in a bit. Also, recall that the commas around name concatenates the Strings in this case.

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, Adam "The Eckspert" Eck!

                                

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.

To remove the whitespace before and after the nickname, you'll need to including sep='' at the end of your print call. Similarly, if you don't want a newline 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

factorial.py: 8 points

choose.py: 2 points (bonus, optional)

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

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

  • To understand the program better, add a print statement that prints out the sum and the number added in each iteration.
  • Change the program so that it sums the first 10 integers instead of the first 4.
  • Now change it so that it prompts the user for an integer n, then calculates the sum of the first n integers.

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

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

secondcoverter.py: 10 points

README: 2 points

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 Chapter 3 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 a single slash means real division, so 14/4 evaluates to 3.5. A double slash, however, gives the integer component of integer division, and thus 14//4 evaluates to 3. The mod, or remainder operator, is invoked with the percent symbol, and gives whatever value is left over after the integer division. So 14%4 yields 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 the 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 answer in a README file (just a text file named "README" created with any text editor -- Komodo is fine). Don't close this file yet -- in the next two parts you'll be adding to this file.

Part 6 - Wrap Up

In every lab, your last job prior to submission is to complete a brief write-up in a README file. In this case, you've already created a README file, so you'll just be adding to it. This is a chance to reflect upon what you've learned, and give us some basic feedback.

In the same README file you created above, add a sentence or two about what you learned in this lab. Also give an estimate of the amount of time you spent on the lab.

Finally, if you have further thoughts about the lab (e.g. a part that was confusing, helpful, annoying, fun, or challenging), please let us know.

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

  • helloworld.py
  • greetings.py
  • fancy.py
  • sum.py
  • factorial.py
  • secondconverter.py
  • README
  • choose.py (bonus, optional)

Part 8 - 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 log out when you are done (either the red-arrow icon at the bottom of your screen, or System->Logout).