P ython p rogramming e xercises


Special Cases and Gotchas



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə51/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   47   48   49   50   51   52   53   54   ...   124
PythonProgrammingExercisesGentlyExplained

Special Cases and Gotchas 
The random.shuffle() function only works with list values and not string values. This is why 
we add single-character strings to a list, shuffle it, and combine that list of strings into a single string 
with the join() string method. Otherwise, passing a string to random.shuffle() results in a 
TypeError: 'str' object does not support item assignment
error message. 
Now try to write a solution based on the information in the previous sections. If you still have 
trouble solving this exercise, read the Solution Template section for additional hints. 
Solution Template 
Try to first write a solution from scratch. But if you have difficulty, you can use the following 
partial program as a starting place. Copy the following code from https://invpy.com/passwordgenerator-
template.py and paste it into your code editor. Replace the underscores with code to make a working 
program: 
# Import the random module for its randint() function. 
import ____ 
# Create string constants that for each type of character: 
LOWER_LETTERS = 'abcdefghijklmnopqrstuvwxyz' 
UPPER_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
NUMBERS = '1234567890' 
SPECIAL = '~!@#$%^&*()_+' 
# Create a string that has all of these strings combined: 
ALL_CHARS = LOWER_LETTERS + ____ + ____ + ____ 
def generatePassword(length): 
# 12 is the minimum length for passwords: 
if length ____ 12: 
length = ____ 
# Create a password variable that starts as an empty list: 
password = [] 
# Add a random character from the lowercase, uppercase, digits, and 
# punctuation character strings: 
password.append(LOWER_LETTERS[random.randint(0, 25)]) 
password.____(UPPER_LETTERS[random.randint(0, ____)]) 
password.____(NUMBERS[random.randint(0, ____)]) 
password.____(SPECIAL[random.randint(0, ____)]) 
# Keep adding random characters from the combined string until the 
# password meets the length: 
while len(password) < ____: 
password.append(ALL_CHARS[random.randint(____, 74)]) 
# Randomly shuffle the password list: 
random.shuffle(____) 
# Join all the strings in the password list into one string to return: 
return ''.join(____) 
The complete solution for this exercise is given in Appendix A and 
https://invpy.com/passwordgenerator.py. You can view each step of this program as it runs under a 


Python Programming Exercises, Gently Explained 
61 
debugger at https://invpy.com/passwordgenerator-debug/

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   47   48   49   50   51   52   53   54   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin