Skip to main content

Section 2.3 Programming with Data

Preview Activity 2.3.1.

Consider the following code that prints out the first ten square counting numbers.

print(f"0^2={0**2}")
print(f"1^2={1**2}")
print(f"2^2={2**2}")
print(f"3^2={3**2}")
print(f"4^2={4**2}")
print(f"5^2={5**2}")
print(f"6^2={6**2}")
print(f"7^2={7**2}")
print(f"8^2={8**2}")
print(f"9^2={9**2}")
Listing 2.3.1. Ten square counting numbers

(a)

Copy this program into a code cell, and modify it to print out the squares from 0 to 14.

(b)

Write a sentence about what you notice about the provided code. What do you think could be improved to make this code more elegant?

Activity 2.3.2.

Usually you will want to not only store collections of data, but do something with each datum. A for loop allows you to deal with data piece-by-piece.

(a)

Save the following numbers as a list named favorite_numbers.

\begin{equation*} 18, 7, -7, -\frac{7}{2}, 9, \frac{17}{4}, 0, -17, 19, 3 \end{equation*}

(b)

Adapt the partial example shown in 2.3.2 to display output similar to 2.3.3 for each number.

for number in favorite_numbers:
    # code indented four spaces right will run for each
    # "number" in the list of "favorite_numbers"
    squared = number**2
    print(f"{number} squared is {squared}")
    # TODO add more information about each number
    # (don't forget to indent!)

# Because we removed the indent, this only
# happens after all numbers are looped through.
print("All done looping!")
Listing 2.3.2. Looping over a list of numbers
18 squared is 324
18 divided by two is 9
18 plus seven is 25
18 minus one half is 17.5
18 times three is 54
Listing 2.3.3. Sample output for each number

(c)

To deal with pairs of data, for loops can also be nested. Adapt the code shown in 2.3.4 to create output as shown in 2.3.5.

for first in range(10):
    for second in range(10):
        print(f"{first} is first, and {second} is second")
Listing 2.3.4. Nested for loops
0 times 0 is 0
0 times 1 is 0
[...]
5 times 9 is 45
6 times 0 is 0
6 times 1 is 6
6 times 2 is 12
[...]
Listing 2.3.5. Excerpt of desired output

Activity 2.3.3.

Often the way you want to deal with data is conditional, that is, the code you want to run will depend on if a variable satisfies a certain condition.

(a)

Paste the code in 2.3.6 into three code cells, changing the value of money_in_bank so that each cell outputs a different response.

money_in_bank = "this probably should be a number, huh"

if money_in_bank > 10000:
    print("Wow you're rich!")
elif money_in_bank > 100:
    print("Hey, not bad.")
else:
    print("I should save up a bit more.")
Listing 2.3.6. Conditional on amount of money

(b)

Bugfix the code shown in 2.3.7.

from math import sqrt # makes the square root function available in Python

for number in favorite_numbers:
    root = sqrt(number)
    print(f"The square root of {number} is {root}")
    # TODO add if/else statements to handle numbers when square root is not allowed
    # print(f"Taking the square root of {number} is not allowed!")
Listing 2.3.7. Using conditionals inside loops

Activity 2.3.4.

A common exercise in entry-level programming interviews is known as “FizzBuzz”. Write a program that for each of the numbers \(1\) through \(100\) prints that number, the word “Fizz” if that number is divisible by \(3\text{,}\) and “Buzz” if that number is divisible by \(5\text{.}\) Example output for the numbers \(1\) through \(15\) is given in 2.3.9.

The code in 2.3.8 implements FizzBuzz in Python, but the lines are out of order and missing indentation. Fix the code to correctly display output as in 2.3.9.

fizz = ""
print(f"{number}{fizz}{buzz}")
fizz = " Fizz"
if number % 3 == 0: # if number is divisible by three
buzz = ""
else:
buzz = " Buzz"
max_number = 100
else:
for number in range(1,max_number+1):
if number % 5 == 0:
Listing 2.3.8. Scrambled FizzBuzz program
1
2
3 Fizz
4
5 Buzz
6 Fizz
7
8
9 Fizz
10 Buzz
11
12 Fizz
13
14
15 Fizz Buzz
Listing 2.3.9. Beginning FizzBuzz output.

Exercises Exercises

1.

Use the code from string import ascii_lowercase; letters = list(ascii_lowercase) to obtain a list of the lowercase English alphabet. Then print(letters) to display them as the output of your code cell.

2.

The line for count,letter in enumerate(letters): allows you to loop through each letter in letters while also keeping count of where you are in the loop (starting with the first counting number \(0\)).

Use enumerate to produce the output shown below.

Letter 0 is a.
Letter 1 is b.
[...]
Letter 25 is z.

3.

Copy your code from the previous exercise, and modify it using ord(letter) to display the following output instead.

Letter 0 is a, which has Unicode value 97.
Letter 1 is b, which has Unicode value 98.
[...]
Letter 25 is z, which has Unicode value 122.

4.

Scrabble 1  is a popular crossword-style game. Like most word games, deciding on what word is best to play is often a mathematical exercise.

First, save https://raw.githubusercontent.com/zeisler/scrabble/master/db/dictionary.csv as the file dictionary.csv in the same folder as this notebook.

Then unscramble the code in 2.3.10 to create nested loops that count the number of vowels used in each of the first fifty words of the Scrabble dictionary.

## LEAVE THIS FIRST
with open("dictionary.csv", "r") as words_file:
    words = [word[:-1] for word in words_file.readlines()[:50]]

## UNSCRAMBLE/INDENT THE REST
print(f"The number of vowels in {word} is {num_of_vowels}.")
num_of_vowels = num_of_vowels + word.count(vowel)
for word in words:
for vowel in ["a","e","i","o","u"]:
num_of_vowels = 0
Listing 2.3.10. Scrambled vowel-counting program

5.

Copy your code from the previous exercise, and then replace the print line with an if/elif/else conditional to produce output similar to 2.3.11.

Boo... the word aa has less than three vowels...
Boo... the word aah has less than three vowels...
Okay. The word aahed has exactly three vowels.
[...]
Wow! The word aardwolves has more than three vowels!
[...]
Listing 2.3.11. Conditional vowel-counting output
https://scrabble.hasbro.com/en-us