我不知道这段代码有什么问题

时间:2015-04-24 16:37:50

标签: python random

所以我希望这段代码按照list1到list2到list3的顺序从每个列表中选择一个随机项。然后我希望它将它们放入随机生成的句子中:

from random import randint

list1 = ["Artless", "Bawdy", "Bootless"]

list2 = ["Base-court", "Bat-fowling", "Beetle-headed"]

list3 = ["Apple-john", "Baggage", "Bladder"]

import random

def nurd3(): 
  print (random.choice(list1))

def nurd2():
    print (random.choice(list2))

def nurd1(): 
   print (random.choice(list3))


print ("Thou" + nurd1() + nurd2() + nurd3())

3 个答案:

答案 0 :(得分:4)

每个功能

中需要return而不是print
def nurd3(): 
  return random.choice(list1)

def nurd2():
    return random.choice(list2)

def nurd1(): 
   return random.choice(list3)

答案 1 :(得分:0)

您的功能是打印项目,而不是返回字符串,因此您无法使用它们在最后一次打印中连接字符串。这些函数都返回None

答案 2 :(得分:0)

主要问题是您从函数中返回值的函数中混淆了打印值。

当您打印该值时,该值只会打印到解释器。当您返回该值时,函数调用将计算为该值,这就是您想要的值。

所以,而不是

def nurd3(): 
  print (random.choice(list1))

使用此

def nurd3(): 
  return (random.choice(list1))

另请注意,您需要在单词周围留出空格。实现这一目标的最佳方法是:

print ("Thou {n1} {n2} {n3}".format(n1=nurd1(), n2=nurd2(), n3=nurd3()))
相关问题