【问题标题】:How can I choose a random conversation output in Python?如何在 Python 中选择随机对话输出?
【发布时间】:2021-03-02 15:07:07
【问题描述】:

我试图让我的脚本在三个对话选项之间进行选择,标记为 petconvo1、petconvo2 或 petconvo3。该程序询问用户有什么宠物,然后随机选择一个关于它们的内容。根据脚本选择的花絮,我想在那里继续对话。我的问题是它只是停止并且没有继续进行对话。最好的方法是什么?

我的代码如下。

#imports the random module
import random
#Asks what pet the user has
pet = input("What kind of pet do you have? ")

#Sets the input to lowercase
petlower = pet.lower()

#Sets tidbits of conversation about the pet
petconvo1 = ("Oh, I've heard that " + petlower + " is a good companion to have.")
petconvo2 = ("Oh, really? I had " + petlower + " when I was growing up.")
petconvo3 = ("Does it cost a lot to keep " + petlower + " fed?")
 
#Turns the tidbits into a list
petconvolist = [petconvo1, petconvo2, petconvo3]

#Compliments pet
print(random.choice(petconvolist))

    
#Continues the conversation
if petconvolist == petconvo1:
    time.sleep(1)
    print("Wouldn't you agree?")
else:
    if petconvolist == petconvo2:
        time.sleep(1)
        print("I think it's important for children to grow up with pets.")
    else:
        if petconvolist == petconvo3:
            time.sleep(1)
            foodbudget=input("Does it cost a lot to feed " + petlower + "?")
            time.sleep(.5)
                                
        else: pass

脚本在此位之后停止:

print(random.choice(petconvolist))

提前致谢!

【问题讨论】:

  • 您需要将随机选择存储在一个变量中,并在if语句中使用它进行比较
  • @Aziz 哦,明白了。谢谢!

标签: python if-statement random


【解决方案1】:

hmm 首先在 if 语句中你应该使用 elif 语句。之后,您应该使用将随机选择设置为 var 以检查它。这段代码对我有用。

#imports the random module
import random
#Asks what pet the user has
pet = input("What kind of pet do you have? ")

#Sets the input to lowercase
petlower = pet.lower()

#Sets tidbits of conversation about the pet
petconvo1 = ("Oh, I've heard that " + petlower + " is a good companion to have.")
petconvo2 = ("Oh, really? I had " + petlower + " when I was growing up.")
petconvo3 = ("Does it cost a lot to keep " + petlower + " fed?")
 
#Turns the tidbits into a list
petconvolist = [petconvo1, petconvo2, petconvo3]

#Compliments pet
convo = random.choice(petconvolist)
print(convo)

    
#Continues the conversation
if convo == petconvo1:
    time.sleep(1)
    print("Wouldn't you agree?")
elif convo == petconvo2:
        time.sleep(1)
        print("I think it's important for children to grow up with pets.")
elif convo == petconvo3:
            time.sleep(1)
            foodbudget=input("Does it cost a lot to feed " + petlower + "?")
            time.sleep(.5)              

【讨论】:

  • 完美!.@NickNterm.
  • 啊,太完美了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2012-11-01
  • 2021-09-29
相关资源
最近更新 更多