Rainmaker Rainmaker - 2 months ago 10
Python Question

IndexError after running program multiple times

After running my program that generates passwords multiple times I get an IndexError: list Index out of range. I am not sure what is causing the problem

import string
import random

def random_pass(length):
alphabet = list(string.ascii_letters + string.digits + string.punctuation)
password = []
upper_case = list(string.ascii_uppercase)
count = 0
while count < length:
random_num = random.randint(0,len(alphabet))
password.append(alphabet[random_num])
#Checks to see if first character is a uppercase Letter
if password[0] not in upper_case:
first_letter = random.randint(0,len(upper_case))
password[0] = upper_case[first_letter]
count += 1
return ''.join(password)
def welcome():
print("*****************************************************************")
print("*****************************************************************")


def main():
try:
get_length = int(input("Please enter the length of your password "))
except ValueError:
print("Please enter numbers only")
main()
else:
print("Your {} character password is {}".format(get_length, random_pass(get_length)))
restart = input("Do you wish to create another password? y/n")
password = []
if restart.lower() == 'y':
main()
else:
exit()
main()

Answer

random.randint can generate the end value as well; you'd need to use random.randrange to generate random numbers in the range that includes the start value and excludes the end.

Comments