当我选择2个字母,2个符号和2个数字时,它可以工作,但是当我选择每个例子40个数字,40个符号和40个数字时,它不起作用,说
当我选择两个字母,两个符号和两个数字时,它可以工作,但不是每个数字都可以
说:
Traceback(最近一次调用):文件"main.py",第866行Symbols_password += symbols[random.randint(0,len(symbols))]IndexError: list index out of range
上面写着这条线不在射程内信[random.randint (0, len(字母)))
我的代码import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?n"))
nr_symbols = int(input(f"How many symbols would you like?n"))
nr_numbers = int(input(f"How many numbers would you like?n"))
letters_password = ""
symbols_password = ""
number_password = ""
if int(nr_letters) <= 50 and int(nr_symbols) <= 50 and int(nr_numbers) <= 50:
for generator_letters in range(0,int(nr_letters)):
letters_password += letters[random.randint(0,len(letters))]
for generator_symbols in range(0,int(nr_symbols)):
symbols_password += symbols[random.randint(0,len(symbols))]
for generator_numbers in range(0,int(nr_numbers)):
number_password += numbers[random.randint(0,len(numbers))]
else:
if nr_letters > 50 and nr_symbols > 50 and nr_numbers > 50:
print("you chose too many letters,symbols and numbers.n The maximum is 50 of each")
elif nr_letters > 50 and nr_symbols > 50 :
print("you chose too many letters and symbols.n The maximun us 50 of each")
elif nr_letters > 50 and nr_numbers > 50:
print("you chose too many letters and numbers.n The maximun us 50 of each")
elif nr_symbols > 50 and nr_numbers > 50:
print("you chose too many symbols and numbers.n The maximun us 50 of each")
elif nr_numbers > 50:
print("you chose too many numbers, the maximum is 50")
elif nr_letters > 50:
print("you chose too many letters, the maximum is 50")
elif nr_symbols > 50:
print("you chose too many smybols, the maximum is 50")
password =(str(letters_password)+ str(symbols_password) + str(number_password))
print(password)
是的,你的问题是random.randint()
函数的一个小怪癖。random.randint()
在之间选择一个随机整数,并包含您给它的第一个和第二个参数,这意味着它实际上可以选择您给它的第二个参数作为输出。看到len(symbols)
实际上并不是一个符号索引,你一定会偶尔遇到IndexError
。每次调用random.randint()
时,从第二个参数中减去1
,就可以了。例如:
symbols_password += symbols[random.randint(0,len(symbols)-1)]
从随机模块docs:
随机的。randint (a, b)
返回一个随机整数N,使得a <= N <= b。randrange(a, b+1)的别名。
所以范围包括len(symbols)
。
由于python使用基于0的索引,因此symbols[len(symbols)]
是IndexError
。
解决方案:使用random.randrange()代替,或者从第二个参数减去1到randint()。
我认为这里有什么问题,你试图使用这个方法与字符串数据你有在你的列表
random.randint()它所做的是:随机。randint (a, b)返回一个随机整数N使得a <= N <= b.别名为randrange(a, b+1)。
所以请尝试使用random.choice(letters)
方法。
和参考随机库DOCS.py获取更多关于随机库
的信息。