Class 9

Objectives for today

1. Practice implementing functions that loop over strings
2. Use functions from the random module

Building up strings

In many of our functions will use a similar pattern in which we build up a new string piece-by-piece by appending characters to a result string (initialized as the empty string or ""). We saw some examples of this pattern previously and now want to implement another example. Specifically we want to write a function named password_gen that takes a single parameter length and generates a random password (as a string) of length characters.

How could we implement our password generator? Show a possible approach

There are many ways, but a simple one is to use randint to index into a string of allowed characters. More formally, this is an example of sampling with replacement, that is every time we sample an item from a set of potential items, e.g. the letters, we replace it in the set so it could be sampled again in the future. An alternative is “sampling without replacement”, in which each item can only be selected once. For this application, why would sampling with replacement be preferred?

As always we want to solve this problem in several steps, instead of trying to tackle the whole problem at once. What are some possible intermediate steps? As an example, I would start by defining a constant CHARS with the allowed characters. Some possible next steps

1. Define a constant CHARS with the allowed characters
2. Create a version of password_gen to create a string of the specified length with a fixed character
3. Enhance password_gen to create a string with random characters

Now let’s implement those steps. Show a possible implementation

1. Define a constant CHARS with the allowed characters

 CHARS = "abcdefghijklmnopqrstuvwxyz0123456789_!@#$%^&*"  2. Create a version of password_gen to create a string of the specified length with a fixed character  CHARS = "abcdefghijklmnopqrstuvwxyz0123456789_!@#$%^&*"

result = ""
for i in range(length):
result = result + CHARS[0]
return result

3. Enhance password_gen to create a string with random characters

 from random import randint

CHARS = "abcdefghijklmnopqrstuvwxyz0123456789_!@#$%^&*" def password_gen(length): result = "" for i in range(length): result = result + CHARS[randint(0, len(CHARS)-1)] return result  Recall that randint has an inclusive end, and so to not exceed the length of CHARS we need to use len(CHARS)-1 as the end argument. 4. And finally add the finishing touches, e.g. docstrings.  from random import randint CHARS = "abcdefghijklmnopqrstuvwxyz0123456789_!@#$%^&*"

"""