Hacking Secret Ciphers with Python

(Ann) #1
Chapter 10 – Programming a Program to Test Our Program 143

The random.randint() Function


transpositionTest.py


  1. for i in range(20): # run 20 tests


  2. Generate random messages to test.






  3. The message will have a random length:



  4. message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40)


The code that does a single test will be in this for loop’s block. We want this program to run
multiple tests since the more tests we try, the more certain that we know our programs work.


Line 13 creates a random message from the uppercase letters and stores it in the message
variable. Line 13 uses string replication to create messages of different lengths. The
random.randint() function takes two integer arguments and returns a random integer
between those two integers (including the integers themselves). Type the following into the
interactive shell:





import random
random.randint(1, 20)
20
random.randint(1, 20)
18
random.randint(1, 20)
3
random.randint(1, 20)
18
random.randint(100, 200)
107





Of course, since these are pseudorandom numbers, the numbers you get will probably be different
than the ones above. Line 13 creates a random message from the uppercase letters and stores it in
the message variable. Line 13 uses string replication to create messages of different lengths.


References


Technically, variables do not store list values in them. Instead, they store reference values to list
values. Up until now the difference hasn’t been important. But storing list references instead of
lists becomes important if you copy a variable with a list reference to another variable. Try
entering the following into the shell:

Free download pdf