## Session 6

### Passing Efficiency

Your first homework problem asked you to compute passing efficiency using the NFL's formula.

```    passes_completed = 185
passes_attempted = 313
passing_yards    = 2450
touchdown_passes = 21
interceptions    = 8

C = (100 * (passes_completed / passes_attempted) - 30) / 20
...
I = 2.375 - (interceptions / passes_attempted) * 25
R = 100 * (C + Y + I + T) / 6

passing_efficiency = int(R * 100) / 100.0
```

Then I added user input and fancy output.

Look at and run the final program. Let's see how UNI's QB did, NFL rating-wise, against Iowa.

```    Sawyer Kollmorgen 17/37 380 2 2
```
A tough day against a good defense. (Still, much better than Alex Smith, Joe Flacco, Tom Brady, Tony Romo, and Eli Manning did in Week 1!)

Notes.

• Start with hard-coded inputs. Replace with user input later. You have the data coded, from experiments in the shell. You know the correct answer. You can move faster getting the rest of the code working before handling the I/O, which is generally pretty straightforward.

• When are one-letter names okay? The names C, Y, T, and R could be better. But coming up with full-word names that are different from the data value names is a challenge. If the people in the problem domain use abbreviated names, sometimes they work well in code. But use them rarely, and with care.

### Population Growth

Your second homework problem asked you to predict the US population in a future year, based on the current rates of birth, death, and net migration. Same M.O.:

```    starting_population = 318817047
starting_year       = 2014
target_year         = 2019

total_seconds = int(total_years * 365.25 * 24 * 60 * 60)

births            = total_seconds // 8
deaths            = total_seconds // 13
net_migration     = total_seconds // 38

ending_population = starting_population + births  \
- deaths  \
+ net_migration
```

Then I added user input and fancy output.

Look at and run the final program.

Notes.

• Don't "precompile" data into your programs.

Why not multiply the total years by 31557600, or combine the rates of change into a single net rate of +1 person every 12 seconds?

First, let the language do the work for you. Second, and more important, using raw daya makes the program easier to modify and reuse. The users' needs may change; perhaps they would like to predict the population on a specific day in the future. The data itself may change; the birth and net migration rates had changed since you textbook was published!

• Why use integer operations? People don't come in 0.12 or 0.77641 parts.

### Rot13

Your first lab exercise yesterday asked you to implement a simple version of rot13. The idea similar to something you did in lab last week and we reviewed in class last Thursday.

```    >>> 'a' <= 'm'
True
>>> ord('a') + 13
110
>>> chr(ord('a') + 13)
'n'
```

We can grow our boolean expression in small steps:

```    >>> 'a' <= 'e' and 'e' <= 'm'
True
>>> 'a' <= 'w' and 'w' <= 'm'
False

>>> char = 'a'
>>> 'a' <= char and char <= 'm'
True
>>> char = 'r'
>>> 'a' <= char and char <= 'm'
False
```

Then we use the expression as the condition on an if statement, in a program file:

```    char = 'e'

if (char >= 'a') and (char <= 'm'):
# change char to the one 13 ahead of it
else:
# change char to the one 13 behind it
```

... and plug in the code for converting characters if statement:

```    char = 'e'

if (char >= 'a') and (char <= 'm'):
char = chr( ord(char) + 13 )
else:
char = chr( ord(char) - 13 )

print(char)      # to see the result
```

Now that we can convert a single character, we want to do the same thing for every character in a string, which is a collection of characters. That's just what a for statement can do for us:

```    for char in ________:
#---------------------------------#
if (char >= 'a') and (char <= 'm'):
char = chr( ord(char) + 13 )
else:
char = chr( ord(char) - 13 )
print(char)
#---------------------------------#
```

The name you use in the code that becomes your suite of statements becomes the "for" variable in the loop statement. The name of the data value being processed is the the "in" variable.

We need a string to process. Following the same plan we've followed all day, we can hardcode a string in for testing:

```    name = 'eugene'
for char in name:
if (char >= 'a') and (char <= 'm'):
char = chr( ord(char) + 13 )
else:
char = chr( ord(char) - 13 )
print(char)
```

Now we can "softcode" the string by asking for user input.

Look at and run the final program. Run V1 (output on one line) and V2 (allows non-lowercase, non-alphabetic characters).

Notes.

• Don't "precompile" data into your programs. Many of you wanted to put ASCII values in your code to compare. The only place we need a number is when we ±13 to the unencoded character's ASCII value. We all understand the characters better. Use them when you can. The programs will be easier to write and read.

• Ideas in computer science build on one another. Part of my job is not let this overwhelm you. I will try not to let us get too deep. Part of your job is to study the things we learn, so that you can use them. What you learned yesterday matters. This is true in other areas of study, but sometimes it's easier to get by with 'holes'.

### The High-Low Game

Your second lab exercise yesterday asked you to implement a computer player for the High-Low game. Most of you didn't get there. Sorry. Let's solve it together.

The spec says:

Your program should behave as follows:
1. Decide on its first guess.
2. Ask the user Is your number X?, putting its guess in for the X.
3. While the user responds something other than yes,
• Decide on its next guess, perhaps using the answer of higher or lower in the process.
• Ask the user Is your number X?, putting its new guess in for the X.
4. Announce to the user that the program won.

Your program can create its new guess any way you want...

In this case, the assignment gives you the algorithm that is the backbone of your code. Use it! Open a new program file:

```    # 1. Decide on its first guess.

# 2. Ask the user "Is your number X?", putting its guess in
#    for the X.

# 3. While the user responds something other than yes,
#    a. Decide on its next guess, perhaps using the answer
#       of higher or lower in the process.
#    b. Ask the user "Is your number X?", putting its new
#       guess in for the X.

# 4. Announce to the user that the program won.
```

... fill in the blanks. Leave the while statement for last.

```    # 1. Decide on its first guess.
guess = 1

# 2. Ask the user "Is your number X?", putting its guess in
#    for the X.

# 3. While the user responds something other than yes,
??????????

#    a. Decide on its next guess, perhaps using the answer
#       of higher or lower in the process.
guess = guess + 1

#    b. Ask the user "Is your number X?", putting its new
#       guess in for the X.

# 4. Announce to the user that the program won.
print("I won!")
```

The program has to keep guessing until the user says 'yes'. That is, the program stops guessing if user says 'yes', and continues otherwise. So: while answer != 'yes': That's just what the algorithm says...

```    guess = 1

guess = guess + 1

print("I won!")
```

We haven't talked about the mechanics of while loops in detail yet, but you have read about them and seen them in class. And the assignment gave you the algorithm. This was doable, if you had time to get to it.

Look at and run the final program.

Notice, as the lab exercise said, that the suite of statements in the body of a while loop must do something to change the condition's value, or the loop continues forever. (Try it...)

Offer V1 for reading -- or a programming challenge! It finds the user's number much more quickly.

Notes.

• When a problem looks really hard, step back, take a deep breath, and take stock. What does the problem give you? Have you done something before that can help with this problem? Can we simplify the problem to get more quickly? Can I run some experiments in the shell that will help me figure something out?

• Start simple. I know this is hard when everything you see is confusing. It's easy to feel disoriented. Problems in class are designed for you, so they are not meant to confuse you. Trust that you can do it, if only you take small enough steps.

### Wrap Up

• Code -- today's zip file

• Reading -- Read Section 2.2, pages 103-137. Play with the code in a Python shell as you do.

• Homework -- Homework 2 was due today. Homework 3 is available and is due in one week.

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