为什么此代码有时可以工作,但如果我在不同的尝试中输入相同的输入,有时会出错?

问题描述 投票:0回答:1
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"))

password = ""
for i in range(1, nr_letters + 1):
  letter = random.randint(1, len(letters))
  password = password + letters[letter]

for v in range(1, nr_symbols + 1):
  symbol = random.randint(1, len(symbols))
  password = password + symbols[symbol]

for d in range(1, nr_numbers + 1):
  number = random.randint(1, len(numbers))
  print(number)
  password = password + numbers[number]

print(password)

顺便说一句,很抱歉代码看起来很丑。我还在学习:)

我运行程序,输入例如 5 个字母、5 个符号和 1 个数字,有时我会得到预期的输出,即使用给定参数生成的密码。但有时我会遇到错误。

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    password = password + numbers[number]
IndexError: list index out of range
python
1个回答
0
投票

根据 文档 对于

random.randint

返回一个随机整数 N,使得 a <= N <= b.

因此,有时(随机),结果值可能等于提供的第二个值,即:

len(numbers)

数组是从零开始的,因此数组长度处的索引始终位于数组之外。

将随机数范围缩小1:

number = random.randint(1, len(numbers) - 1)

(其他情况也一样。)

© www.soinside.com 2019 - 2024. All rights reserved.