随机调用一个函数

Call one single function randomly

我正在制作这个聊天回复程序,我的目标是让计算机从数据库中随机选择一个问题并能够根据输入的答案进行回复。没有错误通知,但问题是它问的第一个问题没有 return 答案,它会问列表中的所有问题,而不仅仅是一个问题。我该如何解决?感谢您的帮助!

import random

x=input("What is your name? ")

def feeling():
    return input("How are you feeling right now " +str(x)+"? ")

def homesick():
    return input("Do you miss your home? ")

def miss():
    return input("Who do you miss?")

prompts = [feeling,homesick,miss]
response = random.choice(prompts)()
 
if feeling()==("tired"):
    Tired=['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
    print(random.choice(Tired))

if homesick()==("yes"):
    yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
    print(random.choice(yes))

if miss()==("my mom"):
    print("Mom will be in town soon")

input() returns 一个字符串,不是函数对象。

因此question是一个字符串列表,你不能像random.choice(question)()

那样调用str对象

如果你想提示随机输入,那么你会这样做,例如

prompts = ["How are you feeling right now " +str(x)+"? "]
response = input(random.choice(prompts))

然后,您需要让您的 if 语句使用 response 变量

如果你想要随机函数,你需要 def

def miss():
    return input("What do you miss? ")

prompts = [miss]
response = random.choice(prompts)()

顺便说一下,你应该使用 while 循环,而不是调用函数本身