Session 5

Controlling the Flow of Code


CS 1510
Introduction to Computing


Opening Exercise: Checksum

One way to determine if a message is authentic is to compute a checksum. The sender computes a small value for a message before sending it. The receiver uses the same function to compute a value after receiving it. If the two values differ, then we have reason to believe that the message has been changed along the way. You often see this technique used when downloading a file from a remote server.

Perhaps the simplest way to compute a checksum for a string is to add up the ASCII values of its characters. For example:

    >>>
    Name    : eugene
    Checksum: 633
    >>>
    Name    : wallingford
    Checksum: 1177

Your task: Fill in the blank in this program to compute the sum of the name's characters:

    name = input("Name    : ")

    # --- THE BLANK --- #

    print("Checksum:", checksum)

Recall from Lab 2 that the ord() function will give us the ASCII value for any character. Your reading for today taught you the new Python you need to solve this problem: the for statement. (See pages 93-94.)



Filling in the Blank

Until now, all of our programs have been fixed sequences of statements: Do this, then this, then this. Sometimes, though, we want to execute the same statement or statements several times. For our checksum program, we need to add a value to our sum for each character in the name. That is, we want to do something like this:

    checksum = checksum + ord(char)
for every character in the name the user enters. That's just what the simplest form of Python's for statement does:
    for char in name:
        checksum = checksum + ord(char)

Note:

With this statement, we can begin to do many more complex things in programs that operate on strings...

Our program needs one more statement. When we add the value of the name's first letter to checksum, what is its value? We haven't started yet, so its value is 0. So:

    name = input("Name    : ")

    checksum = 0
    for char in name:
        checksum = checksum + ord(char)

    print("Checksum:", checksum)

This is a common pattern for computing a running total. You will see and use it often.

You can use more than one statement in the body of a for statement. For example, you might want to print each ASCII value before updating the running total:

    for char in name:
        ascii_for_char = ord(char)
        print(ascii_for_char)
        checksum = checksum + ascii_for_char

Quick exercise: Change either version of the program to also count the number of letters in the name.



Boolean Values

Until now, our programs have worked with two kinds of data: strings and numbers. Sometimes, though, we need to make decisions based on whether some condition holds or not. So we need a need kind of value, true/false. These are called boolean values, in honor of George Boole. In Python, the boolean values are True and False.

For example, we can compare numbers using symbols you are familiar with, plus a couple of new ones:

    >>> 0 < 1
    True
    >>> 7 >= 8
    False
    >>> 42 == (21 + 21)
    True
    >>> (3 - 2) != 1
    False

We can use the same symbols to compare strings, too. Try it out!

We can use boolean values in the much the same way as we did numbers and strings. For example:

    >>> answer = 42 == (21 + 21)
    >>> print("Answer:", answer)
    False

But for now, we will mostly use them as part of statements that help us to make decisions. You saw many examples in Section 2.1.



Next Exercise: Capitalizing Initials

First, a new bit of Python... If you have a string, you can access the first character in it using [0]:

    >>> name = 'eugene'
    >>> name[0]
    'e'

Now take look at this program:

    first_name = input("First name: ")
    last_name = input("Last name : ")

    first_char = first_name[0]
    second_char = last_name[0]
    initials = first_char + second_char

    print("Initials  :", initials)

Your task: Modify the program so that it prints out the initials in capital letters, even if I type the name in lowercase:

    >>>
    First name: Eugene
    Last name : Wallingford
    Initials  : EW
    >>>
    First name: george
    Last name : boole
    Initials  : GB

For now, assume that the user enters only alphabetic characters, 'a' through 'z', either upper- or lowercase.

Recall from Lab 2 that we can use ord() and chr() to "build" a new character from an old one. Your reading for today taught you the new Python you need to solve this problem: the if statement. (See pages 83-86.)



Filling in the Blank

What blank? To accomplish our task, we have to see a gap in the first version of the program. Between (1) setting up the first_char and second_char and (2) creating the initials to print, we need to make sure the character is capitalized.

How can convert a lowercase character into an uppercase character? We need to add or subtract an appropriate value to its ASCII value. What is the distance between 'a' and 'A'? Let's find out:

    >>> ord('A') - ord('a')
    -32
    >>> ord('a') - ord('A')
    32

Hmm... 'a''s ASCII value is bigger than 'A''s ASCII value. So, to convert a lowercase letter to its uppercase equivalent, we need to subtract 32 from its value.

Before today, all of our programs were fixed sequences of statements: Do this, then this, then this. Sometimes, though, we want to execute a statement or statements only if some condition holds. For our initials program, we need to capitalize each character only if it is lowercase. That is, we want to do something like this:

    ascii_of_capital = ord(first_char) - 32
    first_char = chr( ascii_of_capital )
but only if first_char is lowercase. That is just what the simplest form of Python's if statement does:
    if first_char > 'Z':
        ascii_of_capital = ord(first_char) - 32
        first_char = chr( ascii_of_capital )

Note:

With this statement, we can begin to compute even more interesting things in our programs...

Our program needs to do this for the second initial, too. If you prefer, you can combine the two statements into one:

    if second_char > 'Z':
        second_char = chr( ord(second_char) - 32 )

This is a common pattern called a guarded action: take this action if the guard allows it. You will see and use it often.

Quick exercise: What if we remove the assumption that the user will enter only alphabetic characters? Modify the program to allow any input:

    >>>
    First name: Eugene
    Last name : Wallingford
    Initials  : EW
    >>>
    First name: george
    Last name : boole
    Initials  : GB
    >>>
    First name: $ugene
    Last name : @allingford
    Initials  : $@

(You will read about the new Python you need for this problem in Section 2.2 of the text.)



Control Structures

Notes become less complete here....

Three fundamental forms of control:

Draw pictures....

The syntax is new, but you'll get the hang of it with practice. Then your attention will turn to the kinds of problems and solutions you see frequently. Different patterns in the code!

With the ideas of selection and repetition, we can now express more interesting algorithms in Python. Work through the examples in Section 2.1 again to see how an idea for solving a problem can be expressed in code, using if, while, and for statements.



Wrap Up



Eugene Wallingford ..... wallingf@cs.uni.edu ..... September 9, 2014