如何在python 3中使用随机数并将字符串连接到另一个字符串random_number次数????
import random
fave_word = 'hello' + 'world'
def randomword(fave_word : str) -> str:
'''Return something'''
rand_num = random.randint(0,3)
for i in range(rand_num):
fave_word += 'Bob'
print(fave_word)
答案 0 :(得分:0)
您需要返回已创建的字符串。或者您可以使用global,但我not recommend that approach:
>>> import random
>>> fave_word = 'hello' + 'world'
>>>
>>> def random_word(word : str) -> str:
... '''Return something'''
... rand_num = random.randint(0,3)
... for i in range(rand_num):
... word += 'Bob'
... return word
...
>>> print(random_word(fave_word))
helloworldBobBobBob
>>> print(random_word(fave_word))
helloworld
>>> print(random_word(fave_word))
helloworldBobBob