# Practice Exercises

Making Paper Cryptography Tools
Chapter 1, Set A
Chapter 1, Set B
The Interactive Shell
Chapter 3, Set A
Chapter 3, Set B
Strings and Writing Programs
Chapter 4, Set A
Chapter 4, Set B
Chapter 4, Set C
The Reverse Cipher
Chapter 5, Set A
The Caesar Cipher
Chapter 6, Set A
Chapter 6, Set B
Chapter 6, Set C
Hacking the Caesar Cipher with the Brute-Force Technique
Chapter 7, Set A
Encrypting with the Transposition Cipher
Chapter 8, Set A
Chapter 8, Set B
Chapter 8, Set C
Chapter 8, Set D
Chapter 8, Set E
Decrypting with the Transposition Cipher
Chapter 9, Set A
Chapter 9, Set B
Chapter 9, Set C
Programming a Program to Test Our Program
Chapter 10, Set A
Encrypting and Decrypting Files
Chapter 11, Set A
Detecting English Programmatically
Chapter 12, Set A
Chapter 12, Set B
Chapter 12, Set C
Chapter 12, Set D
Chapter 12, Set E
Hacking the Transposition Cipher
Chapter 13, Set A
Modular Arithmetic with the Multiplicative and Affine Ciphers
Chapter 14, Set A
Chapter 14, Set B
Chapter 14, Set C
Chapter 14, Set D
The Affine Cipher
Chapter 15, Set A
Hacking the Affine Cipher
Chapter 16, Set A
The Simple Substitution Cipher
Chapter 17, Set A
Chapter 17, Set B
Chapter 17, Set C
Hacking the Vigenère Cipher
Chapter 21, Set A
Chapter 22, Set A
Public Key Cryptography and the RSA Cipher
Chapter 24, Set A
Chapter 24, Set B
Chapter 24, Set C
Chapter 24, Set D

## Practice Exercises 1A

Using the cipher wheel or St. Cyr Slide, encrypt the following sentences with key 5.

1. Eat food.
2. Mostly plants.
3. Not too much.

Using the cipher wheel or St. Cyr Slide, decrypt the following sentences with key 17.

1. Z YRMV DP WRKYVI'J VPVJ.
2. REU DP DFKYVI’J EFJV.
3. ZE R ARI LEUVI DP SVU.

## Practice Exercises 1B

Encrypt the following sentences in the Caesar cipher with the given keys:

1. "AMBIDEXTROUS: Able to pick with equal skill a right-hand pocket or a left." with the key 4.
2. "GUILLOTINE: A machine which makes a Frenchman shrug his shoulders with good reason." with key 17.
3. "IMPIETY: Your irreverence toward my deity." with key 21.

Decrypt the following ciphertexts with the given keys:

1. "ZXAI: P RDHIJBT HDBTIXBTH LDGC QN HRDIRWBTC XC PBTGXRP PCS PBTGXRPCH XC HRDIAPCS." with key 15.
2. "MQTSWXSV: E VMZEP EWTMVERX XS TYFPMG LSRSVW." with key 4.

Encrypt the following sentence with the key 0:

1. "This is a silly example."

Here are some words and next to them the same word encrypted. What key was used?

1. ROSEBUD – LIMYVOX
2. YAMAMOTO – PRDRDFKF
3. ASTRONOMY – HZAYVUVTF

The following sentence was encrypted with the key 8. What does it decrypt to when you use the key 9 instead?

1. "UMMSVMAA: Cvkwuuwv xibqmvkm qv xtivvqvo i zmdmvom bpib qa ewzbp epqtm."

## Practice Exercises 3A

1. What are the operators for addition, subtraction, and multiplication?
2. Which is the operator for division: `/` or `\` ?
3. Which of these is an integer value, and which is a floating point value?
`42`
`3.141592`
4. Which of these lines are not expressions?
`4 x 10 + 2`
`3 * 7 + 1`
`2 +`
`42`

## Practice Exercises 3B

1. If you enter this code into the interactive shell, what does it print out?
```>>> spam = 20
>>> spam```
2. If you enter this code into the interactive shell, what does it print out?
```>>> spam = 20
>>> spam = 30
>>> spam```
3. If you enter this code into the interactive shell, what does it print out?
```>>> spam = 20
>>> spam = spam + 20
>>> spam```
4. If you enter this code into the interactive shell, what does it print out?
```>>> spam = 20
>>> spam + 20
40
>>> spam```
5. If you enter this code into the interactive shell, what does it print out?
```>>> spam = 20
>>> SPAM = 30
>>> spam```
6. If you enter this code into the interactive shell, what does it print out?
`>>> spam = `
7. If you enter this code into the interactive shell, what does it print out?
`>>> monkeyplumber`
8. Which of these lines is an expression, and which of these is a statement?
```>>> 2 + 2
4
>>> spam = 42```
9. Is this line an expression or a statement?
```>>> 5
5```

## Practice Exercises 4A

1. If you enter this code into the interactive shell, what does it print out?
2. ```>>> spam = 'Cats'
>>> spam```
3. If you enter this code into the interactive shell, what does it print out?
4. ```>>> spam = 'Cats'
>>> spam + spam + spam```
5. If you enter this code into the interactive shell, what does it print out?
6. ```>>> spam = 'Cats'
>>> spam * 3```
7. If you enter this code into the interactive shell, what does it print out?
8. `>>> print("Dear Alice,\nHow are you?\nSincerely,\nBob")`
9. If you enter this code into the interactive shell, what does it print out?
10. `>>> print("Hello" + 'Hello')`

## Practice Exercises 4B

If you enter the following pieces of code into the interactive shell, what does it print out?

1. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[0])```
2. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[5])```
3. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[-1])```
4. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[-3])```
5. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[0:4] + spam[5])```
6. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[-3:-1])```
7. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[:10])```
8. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[-5:])```
9. ```>>> spam = 'Four score and seven years is eighty seven years.'
>>> print(spam[:])```

## Practice Exercises 4C

1. Which window has the `>>>` prompt? The interactive shell or the file editor?
2. Which window runs one Python instruction at a time, immediately? The interactive shell or the file editor?
3. What does the following Python instruction print out?
4. `#print('Hello world!')`
5. What function displays text on the screen?
6. What function lets the user type text into the program?
7. What does it mean if your program calls `input()` and you type in `blah`, and the program displays this error:
8. `NameError: name 'Albert' is not defined`

## Practice Exercises 5A

What do the following pieces of code display on the screen?

1. `print(len('Hello') + len('Hello'))`
2. ```i = 0
while i < 3:
print('Hello')
i = i + 1```
3. ```i = 0
spam = 'Hello'
while i < 10:
spam = spam + spam[i]
i = i + 1
print(spam)```
4. ```i = 0
while i < 4:
while i < 6:
i = i + 2
print(i)```

## Practice Exercises 6A

Using the cipher program, encrypt the following sentences with the given keys:

1. “'You can show black is white by argument,' said Filby, 'but you will never convince me.'” with the key 8.
2. “1234567890” with key 21.

Using the cipher program, decrypt the following ciphertexts with the given keys:

1. “'Kv uqwpfu rncwukdng gpqwij.'” with key 2.
2. “Xqp whh ahoa kb pda sknhz swo ejreoexha.” with key 22.

Using the cipher program, encrypt the following sentence with the key 0:

1. “This is still a silly example.”

## Practice Exercises 6B

1. What Python instruction would import a module named `watermelon.py`?
2. The variable `SPAM` is a constant. Will this code cause an error?: `SPAM = 'hello'`

What do the following pieces of code display on the screen?

1. ```for i in 'hello':
print(i)```
2. `print('Hello'.lower())`
3. `print('Hello'.upper())`
4. `print('Hello'.upper().lower().upper().lower())`

BONUS: What does this program display on the screen? (Guess, and then type it in and run it to find out.)

```spam = 'foo'
for i in spam:
spam += i
print(spam)```

## Practice Exercises 6C

What do the following pieces of code display on the screen?

1. ```if 10 < 5:
print('Hello')```
2. ```if 10 < 5:
print('Hello')
else:
print('Goodbye')```
3. ```if 10 < 5:
print('Hello')
elif 5 == 5:
print('Alice')
else:
print('Goodbye')```
4. ```if 10 < 5:
print('Hello')
elif False:
print('Alice')
else:
print('Goodbye')```
5. ```if 10 < 5:
print('Hello')
elif False:
print('Alice')
elif 5 != 5:
print('Bob')
else:
print('Goodbye')```
6. ```if 10 < 5:
print('Hello')
elif 5 == 5:
print('Alice')
else:
print('Goodbye')```
7. ```if 10 < 5:
print('Hello')
else:
print('Goodbye')
elif 5 == 5:
print('Alice')```
8. `print('f' in 'foo')`
9. `print('f' not in 'foo')`
10. `print('foo' in 'f')`
11. `print('hello'.find('o'))`
12. `print('hello'.find('oo'))`

## Practice Exercises 7A

Break the following ciphertexts:

1. R UXEN VH TRCCH,
2. FR DBMMR EHOXL FX,
3. CXPNCQNA FN'AN BX QJYYH,
4. OBR OZKOMG QOFSTFSS.
5. PDKQCD IU DAWZ DWO OQOLEYEKJO,
6. FTMF U WQQB GZPQD YK TMF,
7. AR ITMF YUSTF TMBBQZ,
8. DA D NCMVIF OJ OCZ NDUZ JA V MVO.
9. ZFBI. J'N QSFUUZ TVSF NZ DBU XPVME FBU NF.

## Practice Exercises 8A

With paper and pencil, encrypt the following messages with the key 9 using the transposition cipher. The (s) parts mark a single space. The number of characters has been provided for your convenience.

1. Underneath(s)a(s)huge(s)oak(s)tree(s)there(s)was(s)of(s)swine(s)a(s)huge(s)company, (61 characters)
2. That(s)grunted(s)as(s)they(s)crunched(s)the(s)mast:(s)(s)For(s)that(s)was(s)ripe,(s)and(s)fell(s)full(s)fast. (79 characters)
3. Then(s)they(s)trotted(s)away,(s)for(s)the(s)wind(s)grew(s)high:(s)(s)One(s)acorn(s)they(s)left,(s)and(s)no(s)more(s)might(s)you(s)spy. (96 characters)

## Practice Exercises 8B

In the following programs, is `spam` a global or local variable? Or are there both a global and local variables named `spam`?

1. `spam = 42`
2. ```def foo():
spam = 42```
3. ```spam = 42
def foo():
spam = 42```
4. ```spam = 42
def foo():
print(spam)```
5. ```spam = 42
def foo():
global spam
print(spam)```
6. ```spam = 42
def foo():
global spam
spam = 99
print(spam)```
7. ```spam = 42
def foo():
spam = 99
print(spam)```

## Practice Exercises 8C

What value do each of the following expressions evaluate to?

1. [0, 1, 2, 3, 4][2]
2. [1, 2, 3, 4][2]
3. [[1, 2], [3, 4]][0]
4. [[1, 2], [3, 4]][1]
5. [[1, 2], [3, 4]][0][1]
6. [[1, 2], [3, 4]][1][1]
7. ['hello'][0]
8. ['hello'][0][1]
9. [2, 4, 6, 8, 10][1:3]
10. list('Hello world!')
11. list(range(10))
12. list(range(10))[2]

## Practice Exercises 8D

What value do each of the following expressions evaluate to?

1. len([2, 4])
2. len([])
3. len(['', '', ''])
4. [4, 5, 6] + [1, 2, 3]
5. 3 * [1, 2, 3] + [9]
6. 42 in [1, 2, 3]
7. 42 in [41, 42, 42, 42]

## Practice Exercises 8E

1. What are the four augmented assignment operators?

What do the following pieces of code display on the screen?

1. ```spam = 'hello'
spam += 'world'
print(spam)```
2. ```spam = 3
spam += 3
spam += 3
print(spam)```
3. `''.join(['hello', 'world'])`
4. `' '.join(['my', 'very', 'special', 'mudder'])`

## Practice Exercises 9A

With paper and pencil, decrypt the following messages with the key 9. The (s) parts mark a single space. The total number of characters is already counted for you.

2. A(s)b(s)(s)drottthawa(s)nwar(s)eci(s)t(s)nlel(s)ktShw(s)leec,hheat(s).na(s)(s)e(s)soogmah(s)a(s)(s)ateniAcgakh(s)dmnor(s)(s) (86 characters)

## Practice Exercises 9B

If you enter the following pieces of code into the interactive shell, what does it print out?

1. `>>> math.ceil(3.1)`
2. `>>> math.ceil(3.0)`
3. `>>> math.floor(3.1)`
4. `>>> math.floor(3.0)`
5. `>>> round(3.1)`
6. `>>> round(3.0)`
7. `>>> round(3.5)`
8. `>>> True and True`
9. `>>> True and False`
10. `>>> False and True`
11. `>>> False and False`
12. `>>> True or True`
13. `>>> True or False`
14. `>>> False or True`
15. `>>> False or False`
16. `>>> not True`
17. `>>> not not True`

## Practice Exercises 9C

1. Draw out the complete truth tables for the `and`, `or`, and `not` operators.
2. Which is correct?
• `if __name__ == '__main__':`
• `if __main__ == '__name__':`
• `if _name_ == '_main_':`
• `if _main_ == '_name_':`

## Practice Exercises 10A

1. If you ran this program and it printed the number 8, what would it print the next time you run it?
```import random
random.seed(9)
print(random.randint(1, 10))```
2. What does this program print out?
```spam = [1, 2, 3]
eggs = spam
ham = eggs
ham[0] = 99
print(ham == spam)```
3. What module contains the `deepcopy()` function?
4. What does this program print out?
```import copy
spam = [1, 2, 3]
eggs = copy.deepcopy(spam)
ham = copy.deepcopy(eggs)
ham[0] = 99
print(ham == spam)```

## Practice Exercises 11A

1. Which is correct: `os.exists()` or `os.path.exists()`
2. When is the UNIX epoch?

What do the following expressions evaluate to?

1. 'Foobar'.startswith('Foo')
2. 'Foo'.startswith('Foobar')
3. 'Foobar'.startswith('foo')
4. 'bar'.endswith('Foobar')
5. 'Foobar'.endswith('bar')
6. 'The quick brown fox jumped over the yellow lazy dog.'.title()

## Practice Exercises 12A

1. What is a dictionary file?
2. Why is being able to detect English useful for cryptanalysis?
3. Would a dictionary file that only had a couple hundred words work for detecting English?

## Practice Exercises 12B

1. What is a Python dictionary?
2. Python lists use square brackets [ and ] to type them out. What do dictionaries use?
3. What does the following code print?
`>>> spam = {'name': 'Al'}`
`>>> spam['name']`
`>>> print(spam['name'])`

## Practice Exercises 12C

1. What does this code print?
```>>> spam = {'eggs': 'bacon'} >>> print(len(spam))```
2. What does this code print?
```>>> spam = {'eggs': 'bacon'} >>> print('eggs' in spam)```
3. What does this code print?
```>>> spam = {'eggs': 'bacon'} >>> print('bacon' in spam)```
4. What `for` loop code would print out the values in the following `spam` dictionary?
`>>> spam = {'name': 'Zophie', 'species':'cat', 'age':8}`

## Practice Exercises 12D

1. What are three differences between dictionaries and lists?
2. What does the following print?
`>>> print('Hello, world!'.split())`
3. What is the None value?
4. How many different values does the NoneType data type have?
5. What happens if your code attempts to divide by zero?

## Practice Exercises 12E

1. Where does the `append()` method add values to a list?
2. What is a default argument?
3. What will the following print?
```def spam(eggs=42):     print(eggs) spam() spam('Hello')```
4. What percentage of words in this sentence are valid English words?
"Whether it's flobulllar in the mind to quarfalog the slings and arrows out outrageous guuuuuuuuur."

## Practice Exercises 13A

1. What does this expression evaluate to: `' Hello world'.strip()`
2. Which characters are whitespace characters?
3. Why does `'Hello world'.strip('o')` evaluate to a string that still has o's in it?
4. Why does `'xxxHelloxxx'.strip('X')` evaluate to a string that still has x's in it?

## Practice Exercises 14A

1. What do the following expressions evaluate to?
`11 % 5`
`21 % 7`
`17 % 1000`
`5 % 5`

## Practice Exercises 14B

1. Is 4 a factor of 8?
2. Is 4 a factor of 10?
3. Is 4 a factor of 12?
4. What is the greatest common factor of 10 and 15?
5. What is the greatest common factor of 6 and 8?

## Practice Exercises 14C

1. What does spam contain after executing `spam, eggs = 'hello', 'world'`?
2. The greatest common factor of 17 and 31 is 1. Are 17 and 31 relatively prime?
3. Why aren't 6 and 8 relatively prime?
4. If two numbers are realtively prime, are they also coprime?
5. What's the difference between a divisor and a factor?
6. Write out the code for the Python function that calculates greatest common divisor.

## Practice Exercises 14D

1. In the shift cipher, the symbol's number is added to the key's number. What is done in the multiplicative cipher?

## Practice Exercises 14E

1. What is the multiplicative inverse a number A?
2. What is a modular inverse of A mod C?

## Practice Exercises 15A

1. The affine cipher can be thought of as the combination of which two other ciphers?
2. What is a tuple?
3. How is a tuple different from a list?
4. Why does having Key A be 1 make the affine cipher weak?
5. Why does having Key B be 0 make the affine cipher weak?

## Practice Exercises 16A

1. What does `2 ** 5` evaluate to?
2. What does `6 ** 2` evaluate to?
3. What does the following code print out?
4. ```for i in range(5):
if i == 2:
continue
print(i)```
5. Does the `main()` function of affineHacker.py get called if another program runs `import affineHacker`?

## Practice Exercises 17A

1. Why can't brute force be used against a simple substitution cipher, even with a powerful supercomputer?

## Practice Exercises 17B

1. What does the spam variable contain after running this code?
`spam = [4, 6, 2, 8]`
`spam.sort()`
2. What is a wrapper function?
3. What does `'Hello'.isupper()` evaluate to?
4. What does `'hello'.islower()` evaluate to?
5. What does `'HELLO 123'.isupper()` evaluate to?
6. What does `'123'.islower()` evaluate to?

## Practice Exercises 17C

1. How can you modify an encryption algorithm to encrypt spaces and punctuation characters?

## Practice Exercises 18A

1. What is the word pattern for the word "hello"?
2. Do "mammoth" and "goggles" have the same word pattern?
3. If the variable spam contains a list of lists of strings, how can you display this is an orderly, pretty way on the screen?
4. Which could be the possible plaintext word for the cipherword PYYACAO: ALLEGED, EFFICIENTLY, or POODLE?

## Practice Exercises 19A

1. The vigenere is similar to which other cipher?
2. How many possible keys are there for a simple substitution key with a key length of 10?
* Hundreds
* Thousands
* Millions
* Much, much more than a million

## Practice Exercises 20A

1. What is frequency analysis?
2. What are the six most common letters in English?
3. What does the spam variable contain after running this code?
`spam = [4, 6, 2, 8]`
`spam.sort(reverse=True)`

## Practice Exercises 21A

1. What is a dictionary attack?
2. What does Kasiski Examination of a ciphertext reveal?
3. What two things does converting a list value to a set value with the set() function do?
4. If the spam variable contains ['cat', 'dog', 'mouse', 'dog']. This list has 4 items in it. How many items does the list returned from list(set(spam)) have?
5. What does the following code print?
print('Hello', end='')
print('World')

## Practice Exercises 22A

1. Why is there no "one-time pad" program presented in this chapter?
2. What cipher is the "two-time pad" equivalent to?
3. Would using a key twice as long as the plaintext message make the one-time pad twice as secure?

## Practice Exercises 23A

1. How many primes numbers are there?
2. What are integers that are not prime called?
3. What are two algorithms for finding prime numbers?

## Practice Exercises 24A

1. What's the difference between a symmetric cipher and an asymmetric cipher?
2. Alice generates a public key and a private key. After a while, she accidentally deletes her private key. Will other people be able to send her encrypted messages? Will she be able to decrypt messages previously sent to her?
3. What is authentication and confidentiality? How are they different?

## Practice Exercises 24B

1. What is nonrepudiation?
2. Alice generates a public key and a private key. After a while, she loses her private key. Will she be able to digitally sign documents? Will other people able to verify her previously signed documents?
3. The function call `ord('A')` returns the integer `65`. What does `chr(65)` return?

## Practice Exercises 24C

1. In cryptography, what is a block?
2. What's the data type of the value `b'hello'`?
3. The `encode()` string method returns a value of what data type?
4. The `decode()` bytes method returns a value of what data type?

1. The variable spam contains the list `['cat', 'dog', 'mouse']`. What does it contain after `spam.insert(1, 'hello')` runs?
2. What does the function call `pow(2, 4)` evaluate to?
3. What does the function call `pow(2, 4, 10)` evaluate to?