<p>目前的代码中有几个错误或遗漏。我在下面的代码中提供了一些注释,以突出代码的潜在改进或一些补充。你知道吗</p>
<pre><code>from random import *
# you don't need a semi-colon after the 4
number = 4
def myFunc(length):
# Since we are building a password, we want to start with an empty
# password before the while loop.
password = ''
while length > 0:
rndNumber = randint(0, 51)
# This step builds a new password incrementally. As you go
# through the while loop, it adds a new character to the
# end of the password variable.
password += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[rndNumber]
length -= 1
return password
# you don't need to convert the output to a string using the code above
# since the process builds a string.
mod = myFunc(number)
print(mod)
</code></pre>
<p>正如查尔斯·达菲所说,随机选择()是一个更好的解决方案,使代码更具python风格:</p>
<h2><code>random.choice()</code></h2>
<p>此函数从一系列项目中随机选取(在引擎盖下,字符串被视为序列)。你知道吗</p>
<p>可以在上面的代码中插入这个片段来帮助清理它。你知道吗</p>
<pre><code>letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
letter = random.choice(letters)
password += letter
</code></pre>