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

2024-09-27 07:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

 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(question==”y“)与“if message in random2:question=input(“\ny/n==>;”)”分组

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

注意:我不能将if语句组合为“if x=a and y=b”,因为我希望“if(question==”y“)”在“message in random2: question=input(“\ny/n==>;”),不能同时出现。你知道吗


Tags: 代码ingtmessageinputifblue语句
3条回答

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”如果为真,那么它将请求输入并检查此输入是否为yes。如果“if message in random2”为false,则所有这些都不会发生,而是转到“elif message in random1:”。你知道吗

我相信这就是你要找的。你知道吗

听起来这就是你想做的:-

只需将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")

也许我错过了你想要的,但如果你想要这两个声明背后的对方,这不是做的把戏吗?你知道吗

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")

相关问题 更多 >

    热门问题