【问题标题】:Python loop not fully loopingPython循环没有完全循环
【发布时间】:2020-12-17 22:22:56
【问题描述】:

每当我在 Python 中执行我的循环时,对于数字和符号,我并没有完全循环我的数字。这可能只是一个初学者语法错误,因为我是 python 新手,但我不确定它是什么。

if sizeOfPassword == 9:
    maxNum = 1
    maxSym = 1
if sizeOfPassword > 9:
    maxNum = 5
    maxSym = 4

checkNum = 0
checkSym = 0

while checkSym < 4 and checkNum < 5:
    if checkSym < maxSym:
        password += chr(random.randint(33, 47))
        checkSym = checkSym + 1
    if checkNum < maxNum:
        password += chr(random.randint(48, 57))
        checkNum = checkNum + 1
    

while len(password) < sizeOfPassword:
    password += chr(random.randint(65, 90))
        
l = list(password)
random.shuffle(l)
password = ''.join(l)

print("Your new random password is: " + password)

当 maxNum = 5 时,我得到这样的值:

0'04%-5'VU
4V/"201"Z'
/T/8O951#*
R-84%("54K

我正在寻找这些值有 5 个数字。有什么想法吗?

【问题讨论】:

  • 我认为问题出在:while checkSym &lt; 4 and checkNum &lt; 5:。您希望 and 成为 or。现在,只要满足这两个条件之一,您就退出循环,您可能希望等到两个条件都满足。

标签: python syntax


【解决方案1】:

你可以简化为:

password_list = [chr(random.randint(48, 57)) for i in range(5)] + [chr(random.randint(33, 47)) for i in range(4)]

password_list
['3', '0', '1', '1', '8', '+', ',', '#', ',']

random.shuffle(password_list)

password = "".join(password)

password
'1+018#,,3'

                                                                                                                                             

【讨论】:

    猜你喜欢
    • 2016-01-31
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多