如何添加“ if”语句,以便将某些相关的语句组合在一起

问题描述 投票:-1回答:3
 random1 = ["\nHello"]
 random2 = ["\nHi"]


    message = random.choice(random1 + random2)
    print(message)

if message in random2:
    question = input("\ny/n ==> ")

elif message in random1:
    print("blue")

if (question == "y"):
    print("blue blue blue")

根据上面的代码,我如何将“ if(quest ==“ y”)”与“ if message in random2:问题= input(“ \ ny / n ==>”)“)分组]

换句话说,由于这两个语句都是相关的,我如何将这两个if语句组合在一起,以便在为“ if(question ==” y“)”编写另一个if语句时不会混淆程序,如图所示。上面的代码。

注:我不能仅将if语句组合为“ if x = a和y = b”,因为我希望“ if(question ==“ y”))出现在“ random2中的消息之后:问题=输入(“ \ ny / n ==>”)“,不能同时出现。

python
3个回答
0
投票

也许我错过了您想要的东西,但是如果您想要两个表述彼此落后,这不会奏效吗?

random1 = ["\nHello"]
random2 = ["\nHi"]


    message = random.choice(random1 + random2)
    print(message)

if message in random2:
    question = input("\ny/n ==> ")
    if (question == "y"):
        print("blue blue blue")

elif message in random1:
    print("blue")

0
投票

Python使用空格和文本格式来确定代码的解释。

您必须在嵌套结构中缩进IF语句以实现所需的内容。

if message in random2:
    question = input("\ny/n ==> ")
    if (question == "y"):
        print("blue blue blue")
elif message in random1:
    print("blue")

上面将运行“ if message in random2”如果为True,它将要求输入并检查此输入是否为yes。如果“如果random2中的消息”为false,则不会发生任何情况,而是转到“ random1中的elif消息:”。

我相信这就是您想要的。


0
投票

这样的声音是您想要做的:-

仅将if语句嵌套在正确的位置

import random
random1 = ["\nHello"]
random2 = ["\nHi"]


message = random.choice(random1 + random2)
print(message)

if message in random2:
    question = input("\ny/n ==> ")
    if (question == "y"):
        print("blue blue blue")

elif message in random1:
    print("blue")
© www.soinside.com 2019 - 2024. All rights reserved.