使用if else语句打印随机字符串

时间:2017-09-20 17:41:30

标签: python string if-statement

import random
import time 
greetingsKeyword = ["hello", "hi", "whatsup", "sup"]
geetingresponse = ["hi", "hello", "how you doing?"]
keywordd = random.choice(greetingsKeyword)
resposne = random.choice(geetingresponse)
user_input = input()
if (user_input == greetingsKeyword):
    print (resposne)
else:
    print ("bye")
time.sleep(5)

我无法修复它我试图在互联网上找到答案,但没有:(

1 个答案:

答案 0 :(得分:0)

以下代码会选择random greetingresponse,如果用户的inputrandom greeting匹配,则会打印random response

import random, time
greetingKeywords = ["hello", "hi", "whatsup", "sup"]
greetingResponses = ["hi", "hello", "how you doing?"]
keyword = random.choice(greetingKeywords)
response = random.choice(geetingResponses)
user_input = input()
if (user_input == keyword):
    print(response)
else:
    print("bye")
time.sleep(5)

如果那不是你想要的,那么下面的代码可能会做你想要的。这将检查用户的输入是否为greetings之一(即greetingKeywords)。如果是,则打印random response

import random, time
greetingKeywords = ["hello", "hi", "whatsup", "sup"]
greetingResponses = ["hi", "hello", "how you doing?"]
user_input = input()
if (user_input in greetingKeywords):
    response = random.choice(greetingResponses)
    print (response)
else:
    print ("bye")
time.sleep(5)

希望这会帮助你。 :)也可以作为旁注,你可以在input()电话中添加一个字符串,例如input("enter your greeting")然后打印出来并让用户更清楚。