Goals

Upon successful completion of this lab, you should be able to understand and write programs using strings and lists of strings.


Setup and Practice

Setup

  1. If your lab machine was not started in MacOS when you went to use it, reboot it to MacOS.
  2. Follow these procedures to mount your blue home-directory on the local machine and create a PyCharm project (call it Lab06). You will use PyCharm in the next part, but, it is important that you set up your project now so that if you run into any issue, we can resolve them quickly.

Practice

  1. Answer Question 1 (the vocabulary question) in your writeup.
  2. Strings Practice

    Answer Questions 2–10 in your writeup, which relate to string indexing, concatenation, repetition and slicing.

    For each try to predict the answers using paper. Then test them and experiment using the online Python 3 tutor, after you have a hypothesis for an answer.

    Question 2
    x = 'I am a string'
    y = 'me too'
    print(x[2])
    
    Question 3
    x = 'I am a string'
    y = 'me too'
    print(x[2] + y[1])
    
    Question 4
    x = 'I am a string'
    y = 'me too'
    print(x + y)
    
    Question 5
    x = 'I am a string'
    y = 'me too'
    print(x + y)
    print(x)
    
    Question 6
    x = 'I am a string'
    y = 'me too'
    print(2 * y)
    
    Question 7
    x = 'I am a string'
    y = 'me too'
    print(y[1:5])
    
    Question 8
    x = 'I am a string'
    y = 'me too'
    print(y[:5])
    
    Question 9
    x = 'I am a string'
    y = 'me too'
    print(y[1:])
    
    Question 10
    x = 'I am a string'
    y = 'me too'
    print(y[:])
    
  3. String Method Practice

    Answer Questions 11–17 in your writeup, which relate to string methods and managing lists of strings.

    Again, for each try to predict the answers using paper. Then test them and experiment using the online Python 3 tutor, after you have a hypothesis for an answer.

    Question 11
    x = 'I am a string'
    print(x.upper())
    
    Question 12–13
    x = 'I am a string'
    print(x.lower())
    print(x)
    
    Question 14–15
    x = 'I am a string'
    z = x.split()
    print(z[0])
    print(x)
    
    Question 16
    x = 'I am a string'
    for w in x.split():
        print(w, end="")
    print()
    
    Question 17
    x = 'I am a string'
    y = x.split()
    print(len(y))
    

Part A: Find $1.00 words

Computers internally store all data as sequences of 1s and 0s that can be interpreted as numbers. Therefore, people have agreed on a method for representing text in numeric form. The most common method is a system called Unicode. Using this table, you can see the Unicode representations of some common characters. The "Dec" column gives you each character's representation as a normal (base 10) number. For example, according to the table, 'A' has the numeric value 65.

Python can show you the numeric representation of your text characters. If you have a Unicode character held in variable c, then ord(c) is the numeric representation of that character. So, ord('A') is the value 65.

Python can go the other direction, too; if you have a number stored in variable i, then chr(i) is the character represented by that number. For example, chr(65) is the value 'A'.

You will be writing a program in which it will be useful to turn letters into numbers, so this background and these functions will be helpful.

Instructions

  1. Referencing the Unicode table above, use the Online Python Tutor to answer Question 18 in your writeup.

  2. Before you start programming, read this specification to understand what your final code should do. Step-by-step instructions will follow.

    Specification

    Your program should:

    • Repeatedly ask the user to enter a word, and convert that word to lowercase. (You may assume that the user enters a single word and not a multi-word phrase.) Stop asking when the user enters quit (or QUIT or QuiT or...).
    • If the user did not enter quit, compute the "value" of the user's word where the letter 'a' is worth 1 cent, 'b' is worth 2 cents, etc.
    • Print the value of the user's word in dollars and cents, formatted to two decimal places. For example, if the user's word is worth 37 cents, you should print $0.37.
    • If the user's word was worth exactly 100 cents ($1.00), print "Congratulations!"
    Sample output 1
    Enter a word: QuiT
    
    Sample output 2
    Enter a word: CoFFee
    Your word is worth $0.40.
    Enter a word: accuMulate
    Your word is worth $1.00.
    Congratulations!
    Enter a word: QUIT
    
  3. Create a new Python source code file called lab06a.py:
    """
    Program: CS 115 Lab 6a
    Author: Your name
    Description: This program finds $1.00 words.
    """
    
    
    def main():
    
        # Ask the user for a word, and save the word to a variable.
        # Convert the user's word to lowercase
        # As long as the user's word is not 'quit'...
            # Echo their word back to them
            # Get a new word from them, convert it to lowercase,
            # and save it to the same variable.
    
    
    main()

    As a first step toward the program described in the specification, this program will just repeatedly ask the user for a word and convert it to lowercase, until the user enters quit. It will then repeat that word back to them.

  4. Translate the pseudocode to Python to build this program. It should match the behavior of the below input/output samples:

    Enter a word: QuiT
    
    and
    Enter a word: CoFFEE
    coffee
    Enter a word: teA
    tea
    Enter a word: QUIT
    

  5. Modify your program so that instead of printing the user's word, it prints each of the characters in the lowercase version of the word on a separate line. Sample input/output:

    Enter a word: CoFFEE
    c
    o
    f
    f
    e
    e
    Enter a word: teA
    t
    e
    a
    Enter a word: quit
    

    Hint: Achieving this will require nesting a for loop inside your while loop: your while loop performs one iteration per word, and the for loop will perform one iteration per letter within the word.

  6. Modify your program so that it prints the numeric Unicode value for each character instead of the character itself. Sample input/output:

    Enter a word: CoFFEE
    99
    111
    102
    102
    101
    101
    Enter a word: teA
    116
    101
    97
    Enter a word: quit
    

    Hint: Recall that for a character variable c, you can get its Unicode value with ord(c).

  7. In order to compute the "value" of a word according to our point system, we want the letter 'a' to be worth 1 point, 'b' to be worth 2 points, etc. However, we can see in our output that the Unicode value of 'a' is 97, 'c' is 99, etc. Answer Question 19 in your writeup.
  8. Based on your answers, figure out how you can adjust this output to print 1 for 'a', 2 for 'b', etc. Sample input/output:

    Enter a word: CoFFEE
    3
    15
    6
    6
    5
    5
    Enter a word: teA
    20
    5
    1
    Enter a word: quit
    
  9. Instead of printing the value of each character, add up the values of the characters in each word to produce a total. Print the total once per word. Sample input/output:

    Enter a word: CoFFEE
    Total: 40
    Enter a word: teA
    Total: 26
    Enter a word: 
      quit
  10. Modify the print statements so that they match the specification. Sample input/output:

    Enter a word: CoFFEE
    Your word is worth $0.40.
    Enter a word: teA
    Your word is worth $0.26.
    Enter a word: quit
    
    Note: you can format a numeric variable x to two decimal places using either: round(x, 2) (which produces a rounded float), or the format specifier logic "{0:.2f}".format(x) (which produces a string that represents the rounded float). Both have the same appearance when printed.
  11. Finally, add the logic that produces congratulations for $1.00 words:
    Enter a word: CoFFEE
    Your word is worth $0.40.
    Enter a word: accumulate
    Your word is worth $1.00.
    Congratulations!
    Enter a word: quit
  12. Demo. When your code matches the examples, call an instructor to demo.
  13. Continue to Part B.

Part B: Find average word length in multi-line text

Instructions

  1. Before you start programming, read this specification to understand what your final code should do. Step-by-step instructions will follow.

    Specification

    Your program should:

    • Repeatedly ask the user to enter a line of text. Stop asking when the user enters a blank line (that is, hits Enter without typing any text).
    • Compute and print the average length of all the words the user entered. Our definition of a "word" is a chunk of text set off by whitespace. For example, @#$! is a 4-character "word" by this definition.
    • Your program should be able to handle the case where the user types only a blank line.
    Sample output 1
    Enter some text: This little piggie went to market
    Enter some text: This little piggie stayed home
    Enter some text:
    The average word length is: 4.90909
    
    Sample output 2
    Enter some text:
    You did not enter any words.
    
  2. Create and open a new Python source code file called lab06b.py:
    """
    Program: CS 115 Lab 6b
    Author: Your name
    Description: Computes the average word length of the user's text.
    """
    
    
    def main():
    
    
    main()
    
  3. Write a line of code that asks the user for a line of text and saves it to a variable. Then write a separate line to print the user's input:

    Enter some text: Mary had a little lamb
    You entered: Mary had a little lamb
    
  4. Write a line of code that uses split to split the user's input into a list, and saves that list into a variable.

  5. Replace your current print statement with a statement that prints the number of words in the line you just read.

    Enter some text: Mary had a little lamb
    This line has 5 words.
    
  6. Add some code that loops over all of the words in your list and computes the total number of characters in all of the words. Print this total. For example:

    Enter some text: Mary had a little lamb
    This line has 5 words.
    These words have a total of 18 characters.
    
  7. Put the code you have written so far inside a loop that repeatedly asks the user for a line of text until the user enters a blank line. There are at least two basic approaches for recognizing a blank line using straight-forward code:

    • Option 1: A blank input string will have a length of 0.
    • Option 2: A blank (empty) input string is represented by two quotation marks with nothing between them.
    Also modify your code so that it uses a new variable to add up the number of words on all of the lines and prints that value after all of the input has been entered. Don't worry about the number of characters for now.

    Enter some text: Mary had a little lamb
    These words have a total of 18 characters.
    Enter some text: Jack and Jill went up a hill
    These words have a total of 22 characters.
    Enter some text:
    Total: 12 words
    
  8. If it is not already doing so, modify your code to add the number of characters on all of the lines, instead of just one line at a time:

    Enter some text: Mary had a little lamb
    Enter some text: Jack and Jill went up a hill
    Enter some text:
    Total: 12 words
    Total: 40 characters
    
  9. Instead of printing the total length and the number of words entered, print the average word length for the user's text, and round it to 5 decimal places:

    Enter some text: Mary had a little lamb
    Enter some text: Jack and Jill went up a hill
    Enter some text:
    The average word length is: 3.33333
    
    and
    Enter some text: This little piggie went to market
    Enter some text: This little piggie stayed home
    Enter some text:
    The average word length is: 4.90909
    
  10. Run your program and immediately hit Enter when the user asks you for some text. Your program will probably crash. Answer Question 20 in your writeup, and then write some code to fix this problem if your program did crash. Sample input/output:
    Enter some text:
    You did not enter any words.
    
  11. Make sure your code matches the examples from the specification:
    Enter some text: This little piggie went to market
    Enter some text: This little piggie stayed home
    Enter some text:
    The average word length is: 4.90909
    
    and
    Enter some text:
    You did not enter any words.
    
  12. Demo. When your code matches the sample outputs, call an instructor over to demo. This is also the code you will submit on Moodle this week.
  13. Continue to the next part to submit your program.

Assignment Submission

Instructions

  1. Answer the last question (#21) in your Moodle writeup. Review your answers, and then click the "Next" button at the bottom of the quiz. Once you do that, you should see a "Summary of Attempt" screen.
  2. Click the "Submit all and finish" button. Warning: You must hit "Submit all and finish" so that your writeup can be graded! It is not submitted until you do this. Once you have submitted your quiz, you should see something similar to this at the top of your Moodle window. The important part is that the State shows up as Finished.
    Quiz confirmation
    Please leave this tab open in your browser.
  3. Click on the "Lab 6 code" link in Moodle and open in a new tab. Follow the instructions to upload your source code (lab06b.py) for Lab06. You could either browse for your code or, using a finder window, drag and drop your lab06b.py from your cs115/Lab06 folder to Moodle. You should subsequently see a dialog box which indicates 'Submission Status' as 'Submitted for grading'. Leave this tab open in your browser.
  4. With these confirmation pages open in your browser, you may call an instructor over to verify that you have completed every part of the lab. Otherwise, you are done!