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:
A reminder about the Honor Code - While you are encouraged to discuss the labs with each other, you should never, ever, copy anyone's code, and you should never give a copy or allow someone else to make a copy of your code. Discuss as much as you like with others, but in the end you need to write your own code.
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 the OCTET office in King 125.)Before you login, you will need to get your username and password from the lab instructor.
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.
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.)
Now you need a place to keep all your cs 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. 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):
% 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
You are going to participate in a ritual that has been around since the early 1970's -- the creation of HelloWorld as your first program in a new language. We will use a Python utility called "Idle" to create and edit programs for this class. By the way, the name "Idle" is homage to the comedian Eric Idle, a member of the comedy troupe Monte Python. Guido van Rossum, Python's inventor, was a big fan of Monte Python and the language contains numerous Monte Python references.
There are two ways to access Idle. One is to type
% idle3 into your terminal. The other is through the Development submenu of the Applications Menu. From the long list of programming language tools choose
IDLE (Using Python 3.4)
This brings up a Python command interpreter. If you type 1+1 into the prompt it will respond 2. This command interpreter is very useful -- at any point while you are programming if you aren't sure what an instruction does you can type it into the interpreter to see. Note that Python refers to it as a "shell", which is a common name for command interpreters. Notice that the shell has a File menu, with New File as one of the options. Don't confuse the file and the shell -- we type code into files and run snippets of code in the shell.
Here are six steps involved in creating programs in any 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, such as the one within Idle.
Creating a file
If you haven't already done so, go to the Python shell's File menu and select New File. This will open an empty file that you can type into. Before you start typing select Save As from the file's File menu and save the file as HelloWorld.py in your lab01 folder. Be sure you know where you are saving the file. After you save it you might want to check that it is where you want. Open another terminal, navigate to your lab01 folder:
% cd ~
This should list HelloWorld.py as the only thing in the lab01 folder. Now back in the HelloWorld.py file type the following:
# helloworld.py # Say hello to the world. My first Python program. # # <your name> # <today's date> print("Hello, World!")
The first 5 lines here are comments for human readers; the computer ignores anything on a line after the # symbol. The only actual Python code here is the list line, which is a print statement.
|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 failed to implement your algorithm properly), or back to the Design phase (if your algorithm itself contains a flaw).
Running your Program
The file where you typed your program has a Run menu. One of the options in this menu is
If your program has been changed since you last saved it the system will prompt you for permission to save -- it won't run an unsaved program. Save if necessary, then choose Run Module again.
should appear in the terminal window. If everything went as planned, congratulations! You've just created 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 (well, you might consider your instructor to be your client and like any good business person it is your job to keep your client happy....) , 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. 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 purpose 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!
This will be the first program in which we get input from the user. Create a new file and save it as greetings.py in your lab01 folder. Type the following into this file:
name = input("Enter your name: " print("So, we meet again,", name, "!")
Save this. Before you run it here is what this does:
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 it might print:
Welcome back, Bob "The Blob" Geitz!
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
all on one line, and the cursor will be at the end of that line (not on the next one.)
Here is a program called compare2.py.
# compare2.py # This asks the user for two numbers and prints them in increasing order # x = eval( input( "Enter one number: " ))
y = eval( input( "Enter a second number: " ))
if (x <= y):
print( x, y )
print( y, x )
compare2.py inputs 2 numbers and prints them in increasing order. Your goal is to modify the program into compare3.py, which does the same thing with 3 numbers.
Note: This program needs to "evaluate" the user input as an integer number because the input( ) function returns a string, not a number. You can do this by using the built-in Python "eval" function eval(expression-you-want-to-evaluate)
Inputting a third number is easy. Doing the comparisons properly takes some organization. The easiest way to do this is to have a sequence of conditions that look like this:
if x <= y and y <= z:
print( x, y, z)
You will need a total of 6 conditions because there are 6 (= 3 factorial) ways to order 3 numbers. Test your progam to make sure it is printing the right numbers in the right order. Try a variety of numbers in a variety of numbers. Be sure to try cases where some of the numbers are equal, as in 3 5 3.
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. For sec = 795 we want m = 13 and s = 15.
Similarly, we might want to do the same 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:
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.
# 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.
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.
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? You don't need to hand this in, but thinking about it will help your understanding.
If you followed the Honor Code in this assignment, make a file in your lab01 folder called README that contains the following text:
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
You should have submitted the following files:
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).