簡體   English   中英

隨機調用一個函數

[英]Call one single function randomly

我正在制作這個聊天響應程序,我的目標是讓計算機從數據庫中隨機選擇一個問題,並能夠根據輸入的答案進行響應。 沒有錯誤通知,但問題是它提出的第一個問題沒有返回答案,而是詢問列表中的所有問題,而不僅僅是一個。 我該如何解決這個問題? 感謝您的幫助!

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()返回一個字符串,而不是一個函數對象。

因此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循環, while不是調用函數本身

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM