首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >For循环不是循环。

For循环不是循环。
EN

Stack Overflow用户
提问于 2017-11-05 13:18:08
回答 3查看 153关注 0票数 0

我试图在python中创建一个CD密钥生成器,并以四个块(每个4位长)生成密钥。我使用for循环从所有字母数字字符的列表中生成字符,并将它们附加到字符串chunk1中。

代码语言:javascript
复制
# 4 digits to be generated
for i in range(0, 4):
    chunk1 = ""

    # Choose randomly whether the next character will be a letter or digit
    uld = randint(0, 1)
    if uld == 0:
        character = 'letters'
        # Randomly choose a letter from all upper- and lowercase letters
        selector = randint(0, 51)
    elif uld == 1:
        character = 'digits'
        # Randomly choose a digit from 0-9
        selector = randint(0, 9)

    # Set `chunk1` equal to itself and append the selected digit
    chunk1 = chunk1 + charset[character][selector] # References the `charset` dictionary

charset是一个有两个键的字典,一个用于大写字母和小写字母,另一个用于0-9的数字。

代码语言:javascript
复制
charset = {
    'letters': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
    'digits': '0123456789'
}

问题是,for循环不是生成4个字符,而是生成一个字符,我似乎不知道为什么。我可能遗漏了一些很明显的东西。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-11-05 13:22:23

chunk1在每次迭代中都会被覆盖。

相反,您应该将这些值存储在列表中。您也不需要所有这些字符串连接

代码语言:javascript
复制
output = []

for i in range(0, 4):
    # Choose randomly whether the next character will be a letter or digit
    uld = randint(0, 1)

    if uld == 0:
        character = 'letters'
        # Randomly choose a letter from all upper- and lowercase letters
        selector = randint(0, 51)

     elif uld == 1:
        character = 'digits'
        # Randomly choose a digit from 0-9
        selector = randint(0, 9)

    output.append(charset[character][selector])

print(''.join(output))
票数 2
EN

Stack Overflow用户

发布于 2017-11-05 13:22:59

chunk1 = "",你能把它移到外部循环吗?

票数 0
EN

Stack Overflow用户

发布于 2017-11-05 13:23:55

问题是,您在循环中说是chunk1 = ""。这意味着,每次循环运行时,都会将变量重置为"“。只要把它放在循环之外,它就工作得很好:https://repl.it/Nlkj/0

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47122028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档