首先,你return
在循环中,所以你永远不会循环几次。将其更改为
def random_characters(number):
i = 0
new_string = ''
while (i < number) :
new_string = random.choice(string.ascii_lowercase)
i = i + 1
return new_string # <<< Dedent
random_characters(3)
#>>> 'c'
然后你需要实际构建new_string
,而不是每次都设置它。构建一个list
然后"".join
它:
def random_characters(number):
i = 0
letters = [] # Place to put the letters
while (i < number) :
letters.append(random.choice(string.ascii_lowercase)) # <<< Add the letter
i = i + 1
return "".join(letters) # <<< Join the letters into one string
random_characters(3)
#>>> 'lgp'
然后你应该使用for i in range(number)
而不是while
循环:
def random_characters(number):
letters = []
for i in range(number): # <<< Deals with i for you.
letters.append(random.choice(string.ascii_lowercase))
return "".join(letters)
random_characters(3)
#>>> 'xay'
您可以使用带有列表理解的缩短版本:
def random_characters(number):
# MAGIC!
letters = [random.choice(string.ascii_lowercase) for i in range(number)]
return "".join(letters) # <<< Join the letters into one string
random_characters(3)
#>>> 'yby'
如果你想运行它,你有几个选择。您可以在交互式解释器中运行它:
%~> python -i random_characters.py
>>> random_characters(3)
'zgp'
或者你可以告诉它print
文件中的结果:
print(random_characters(3)) # Python 3
print random_characters(3) # Python 2