以下所有 for 回圈中的變數都表示“未訪問變數 Pylance” 變數的字體顏色為“死”。
if special == "n" and numbers == "n":
for i in range(l):
password.append(random.choice(chars))
elif special == "y" and numbers == "y":
for c in range(l - nos - non):
password.append(random.choice(chars))
for s in range(nos):
password.append(random.choice(special))
for n in range(non):
password.append(random.choice(numerics))
完整代碼
import random
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV"
special = ["@", "#", "$", "%", "&", "*", "."]
numerics = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
password = []
def length(): #ask length
while True:
length = int(input("Enter length: "))
if length > 0:
return length
else:
print("Too short")
def spec(): #ask if want speci char
while True:
needsSpecial = input("Do you need special chracter? (y/n): ")
if needsSpecial == 'y' or needsSpecial == 'n':
return needsSpecial
def numofspecial(): #ask amount of speci char
while True:
specialLen = int(input("How many special charcters?: "))
if specialLen < 1 or specialLen > l:
print("wrong input")
else:
return specialLen
def num(): #ask if want num
while True:
needsNum = input("Do you need numbers? (y/n): ")
if needsNum == 'y' or needsNum == 'n':
return needsNum
def numofnum(): #ask for # of num
while True:
numofnum = int(input("How many numbers?: "))
if numofnum < 1 or numofnum > l or (specials == "y" and numofnum > (l - nos)):
print("wrong input")
elif l - nos == 0:
return numofnum
else:
return numofnum
def main():
password = []
global l
l = length()
if l == 1:
lst = [chars, special, numerics]
password.append(random.choice(random.choice(lst)))
password = ''.join(str(e) for e in password)
print(password)
else:
global specials
specials = spec()
if specials == "y":
global nos
nos = numofspecial()
numbers = num()
if numbers == "y":
global non
non = numofnum()
if special == "n" and numbers == "n":
for i in range(l):
password.append(random.choice(chars))
elif special == "y" and numbers == "y":
for c in range(l - nos - non):
password.append(random.choice(chars))
for s in range(nos):
password.append(random.choice(special))
for n in range(non):
password.append(random.choice(numerics))
print(password)
random.shuffle(password)
password = ''.join(str(i) for i in password)
print(password)
main()
uj5u.com熱心網友回復:
正如評論中提到的,警告的原因是您不使用該變數;python 中的約定是_用于此類變數。您可以通過使用來擺脫這個問題,將您想要的隨機值數量的值random.choices傳遞給它。k我已經修改了您的代碼以簡化它;請注意,如果用戶需要數字或特殊字符,這取決于兩者non并被nos初始化0和修改(未定義):
nos = 0
specials = spec()
if specials == "y":
nos = numofspecial()
non = 0
numbers = num()
if numbers == "y":
non = numofnum()
# ...
noc = l - nos - non
password = []
password = random.choices(chars, k=noc)
password = random.choices(special, k=nos)
password = random.choices(numerics, k=non)
# make a string
password = ''.join(random.sample(password, k=l))
筆記
- 您可以使用簡化字串密碼生成
random.sample - 你有一個錯字
if,你應該使用specials,而不是special。但是,通過此代碼更改,它不再是問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/520435.html
上一篇:變數初始化后拋出初始化錯誤
