Prelab 3 Notes

Here we discuss an interesting problem that has parallels with the work you are doing this week for Prelab 3 and Lab 3. There is nothing to turn in for this write-up – it is just for extra practice.

Building up strings

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 in class and will tackle another example here. Specifically let’s 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? There are many ways, but a simple one is to use randint to index into a string of allowed characters.

Let’s solve this problem in several steps:

  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_!@#$%^&*"
        
     def password_gen(length):
         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 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_!@#$%^&*"
        
     def password_gen(length):
         """
         Generate a random password
            
         Args:
             length: number of characters in the password
                
         Returns:
             Password string
         """
         result = ""
         for i in range(length):
             result = result + CHARS[randint(0, len(CHARS)-1)]
         return result