首先,你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'
如果你是wanti爲了運行這個,你有幾個選擇。要麼你可以在互動解釋器中運行這個:
%~> python -i random_characters.py
>>> random_characters(3)
'zgp'
,或者你可以告訴它print
裏面的文件結果:
print(random_characters(3)) # Python 3
print random_characters(3) # Python 2
這可以幫助:是什麼'return'嗎?沒有什麼是返回](http://stackoverflow.com/questions/19066925/what-does-return-do-nothing-is-ever-returned)和順便說一句,你的'return'語句沒有正確縮進。 –