Laboratory: Programming in Python
CSC 105 - The Digital Age

Summary: In this laboratory, you begin the journey of learning to write computer programs in the Python programming language.

Contents

Exercise 0: Preparation

  1. Open a terminal window. Create a directory in which to store your programs, with the command:
      mkdir 105/code
  2. Move to that directory:
      cd 105/code
  3. Open the text editor gedit, as shown below. (Note that the ampersand in the command is important. It allows you to open gedit, yet retain access to your terminal window.)
       gedit &
  4. Arrange your windows so that you can see the terminal window and gedit at the same time. During this lab and the next few, you will move back and forth between these two windows as you work. Your work cycle will be:

Exercise 1: Your First Program

  1. Your first program will contain a single Python statement. Enter the following statement into a new document in gedit, noting that the quotation marks are important.
    print "Welcome to the wacky world of computer programming!"
  2. Save your work, naming the file first.py. Note that it is important to use the file extension .py. This specifies that your file is a Python program. The dialog box that appears should have a box for Name:. The Save in folder: box should say code. (If it does not, you may need to use the "Browse for other folders" option in order to save your file in your 105/code directory.)

    Note that when you save the file, gedit will automatically colorize the text for you. Much like it did with HTML, the text editor recognizes (from the file name) the "langauge" you are writing in, and uses color/font highlighting to visually help you write and understand your programs.

  3. Run your program in the terminal window, with the following command.
      python first.py
    If all goes well, your program should print the greeting in the terminal window. If that does not happen, try to figure out why, or ask for help.

Exercise 2: Fun With Print Statements

  1. Add a second print statement to your program, as follows:
    print "Are we having fun yet?"
    Save your program, and run it in the terminal window.
  2. When you have that working, modify your program to add a few more lines of text to your output. Note that you can use any punctuation or printable symbol on the keyboard.
  3. Now open a new file in gedit to start writing a new program named figure.py.
  4. In your new file, write a program that draws a figure similar to the one below, using a set of print commands. This kind of drawing is called "ASCII Art" since it is made solely with characters in the ASCII character set.
               * *
              *   *
               * *
                *
              * * *
             *  *  *
            *   *   *
                *
              *   *
             *     *
            *       *
           *         *
          *           *

    Remember to save your work before running your program in the terminal window.

  5. Write a program (create a new file) named ascii.py in which you draw your own ASCII Art design using Python print statements. (Please do give your program this name, because we may come back to it later, and it would be nice to be able to find it easily.)

    Have fun with this exercise, but please only work on your drawing for more more than 5 minutes. We have a lot of fun things left to do!

Exercise 3: Character Strings and Variables

In the previoius exercises, you used character strings, which are more commonly called just strings for short. A string is a single data element, composed of zero or more characters.

When typing a string directly into a program, as we have done, we enclose the string in quotation marks. This tells Python that the enclosed characters comprise a single string. (Note that the quotation marks were never printed in the output. They are not part of the string; rather, they are part of the program used to define the string.)

We can also store a string in a variable. To do so, we use an assignment statement such as the following. This is an instruction that tells Python to store the string "Sue" into a variable named name. We say that the value "Sue" is assigned to the variable name.

name = "Sue"
Please note carefully, that (although it seems strange) the "equals sign" here does not denote equality. Rather, it is an instruction telling Python to assign the value on its right into the variable on its left.
  1. Try this out by entering the following program into a new file called name.py. Be careful to include all the punctuation exactly as specified. The commas in the print statement allow us to give the print command three different arguments: a string, a variable, and another string. If all goes well, each of them will be printed in turn.
    name = "Sue"
    print "Hello " + name + "! how are you?"
    The plus sign is used to concatenate strings (i.e., join them together to form a single new string).
  2. Now save your program and run it. You should also find that the print statement prints the value stored in the variable name, rather than printing the word name itself.
  3. We can also use string concatenation to create new strings and assign them to variables. For example,
    name = "Sue"
    greeting = "Hello, " + name + "! How are you?"
    print greeting
    Here, three strings are joined into one, and that one new string is assigned to the variable greeting. Then the value in greeting is printed. Try out this program to make sure you understand how it works.
  4. We can also ask the "user" (i.e., the person running the program) to input a string for our program to use. To do this, we use statements like the following. Here, raw_input is a subroutine, one of our key algorithm ingredients. We may also refer to a subroutine as a function. Note that it is followed immediately by a pair of parenthesis with a string inside them. This string is an parameter (another of our algorithm ingredients), and we say that we pass it to the subroutine raw_input. We may also call a parameter an argument.The purpose of raw_input is to print its argument, wait for the user to input something, and then return that input as a string. The string will then get assigned to the variable str.
    strn = raw_input("Please enter a string: ")
    print "You typed " + strn
    Try out the code above to see exactly what it does. When you run the program, it should print a prompt asking you for data. It should then wait until you type something and press Enter. Only when you have done that will the program move on to process the print statement.
  5. Write a program called emphasize.py that prompts the user to enter a word, and then prints that word surrounded by a pair of asterisks on each side. For example, a run of your program might look like the following:
    Please enter a word: Hello
    ** Hello **
  6. Write a program called greeting.py that asks the user to enter his or her name and favorite color, and then writes a message that includes that information. For example, a run of your program might look something like this:
    What is your name? Sue
    What is your favorite color? turqoise
    Hi, Sue! I like turquoise too!
  7. Variables are called variables because we can change the values that they store. Consider the following program. What do you expect to be printed when the program is run?
    color = "red"
    print color
    
    color = "blue"
    print color
    Give this program a try to see if it does what you expect. You should see that the original value stored in color ("red") is overwritten by the new value "blue". A variable can hold one only value at a time, so when you assign a new value to a variable, the old value is overwritten.
  8. Add the following statements to the bottom of the previous program. What do you expect will be printed when the program is run?
    hue = "green"
    print hue
    
    color = hue
    print color
    print hue
  9. Run the program to see if you are right. This example should show that we can also assign the value stored in one variable (hue) into another variable (color). Just remember that an assignment statement always assigns the value on the right to the variable on the left.
  10. Write a program, in a file named swap.py, that begins as follows.
    color1 = "red"
    color2 = "blue"
    The purpose of your program is to swap the values in the variables color1 and color2, using only assignment statements. In other words, see if you can do it without having either of the string literals ("red" or "blue") appear anywhere else in your program. You may find it useful to use a third variable to solve this problem.

    You can tell whether your program is successful by ending it with the following statement:

    print color1 + " " + color2
    The output from your program should be:
    blue red

Exercise 4: Index Numbers and String Subscripts

We can also extract (or modify) individual characters within a string. To do so, we need a way to specify which character we mean. This is done by giving each position in the string an index number, which is determined by simply counting off (starting at 0) from left to right. We then use the index number as a subscript into the string. The syntax for doing this is shown in the example below.

For example, if the variable color holds the string "turquoise", then

etc.

  1. Write a program that prompts the user to enter a 6-letter word, and then prints the first, third, and fifth letters of that word. A sample run of your program might look like this:
    Please enter a 6-letter word: sadist
          The first, third, and fifth letters are: s d s
  2. We can also instruct the computer to search for a given character within a string, using a method called index. (A method is very similar to a function or subroutine, but the syntax is a bit different as shown in the example below.) For example, suppose again that the variable color holds the string turquoise. We can retrieve the index of the letter q (which is 3) as follows:
    color = "turquoise"
    index = color.index("q")
    print "The index number for the letter q within the word " + color + " is" , index
    Try this program to convince yourself that it will, in fact, determine the correct index number for the letter q.

    Note: We have used a comma rather than a plus before index above to concatenate the string and a number. As you will learn on the next lab, the difference between these two types of data is important. For now, please take our word that the comma is the "right thing" to do, and a plus would render the program incorrect.

  3. Modify the program to have it search for other characters in the string.
    1. Does it always return the index number you expect?
    2. What index is returned if you ask for the index of the letter u?
    3. What happens when the desired character appears more than once in the string)?

Exercise 5: For Those with Extra Time

a. We can also isolate substrings within a string based on the index values of the characters we are interested in. Try out the following program to see if you can discover how the syntax for substrings works.

color = "turquoise"
print "color = " + color
print "color[0:1] = " + color[0:1]
print "color[2:4] = " + color[2:4]
print "color[1:5] = " + color[1:5]
print "color[3:8] = " + color[3:8]
print "color[:4] = " +  color[:4]
print "color[2:] = " +  color[2:]

b. Write a program called time.py that prompts the user to enter the current time in HH:MM format, and then prints a message that states the time in a sentence. (To begin with, assume that the user will always enter two characters for the hour, even if one would do. Similarly, your program may print two characters, even if one would do.) For example, a sample run of your program might look something like this:

What is the time please (HH:MM)? 06:55
Thanks! It is now 55 minutes after 06 o'clock.

Now modify your program so that it will still work correctly if the user enters one-digit hours using only one digit. For example:

What is the time please (HH:MM)? 2:55
Thanks! It is now 55 minutes after 2 o'clock.
Hint: You may find it handy to use three variables for this problem. First, find and store the index of the colon character. Then use that index to determine and store the hour and the minute values.

c. CHALLENGE PROBLEM:
From a Java lab written by Sam Rebelsky.

You may be familiar with Shirley's Ellis's Name Game. Ms. Ellis describes her procedure for developing phrases based on her colleague's names as follows:

Come on everybody!
I say now let's play a game
I betcha I can make a rhyme out of anybody's name
The first letter of the name, I treat it like it wasn't there
But a B or an F or an M will appear
And then I say bo add a B then I say the name and Bonana fanna and a fo
And then I say the name again with an F very plain
and a fee fy and a mo
And then I say the name again with an M this time
and there isn't any name that I can't rhyme.

She also gives us a number of examples:

Shirley!
Shirley, Shirley bo Birley Bonana fanna fo Firley
Fee fy mo Mirley, Shirley!

Lincoln!
Lincoln, Lincoln bo Bincoln Bonana fanna fo Fincoln
Fee fy mo Mincoln, Lincoln!

Write a program called NameGame.py that gets a name from the user and prints out a verse of the form Ms. Ellis suggests. Your program need not handle names that begin with vowels or with more than one consonant.

Written: Marge M. Coahran, February 2008
Revised: Jerod Weinman, 2 January 2009
Revised: Jerod Weinman, 24 February 2011
Adopted from: CSC105: Programming in Python
Copyright © 2009-2011 Marge Coahran and Jerod Weinman.
CC-BY-NC-SA
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License .