【问题标题】:How to connect these 2 statements in python如何在python中连接这两个语句
【发布时间】:2016-11-22 05:44:56
【问题描述】:
if ask == "yes" or ask == "Yes":
    print("lets go, if you dont know a question you can say 'I dont know' to leave the gameshow")
else:
    if ask == "no" or ask == "No":
     print("then go home")

    exit(ask)

print("What is the capital of Sarajevo?")

if ask == "sarajevo" or ask == "Sarajevo":
  print("Correct, you get to move on")
else:
    if ask == "i don't know" or ask == "I don't know":
     print("Sorry that isn't correct, you lost")
     exit(ask)

无论我尝试什么,它们最终都会被打印出来

【问题讨论】:

  • 你在哪里初始化ask,请输入一个工作代码或至少一些我可以在我的系统上复制和运行的代码。您放置的代码无法运行。 stackoverflow.com/help/mcve
  • “连接这两个语句”是什么意思?
  • 我想连接 2 个 if 语句,将来可能会添加更多。

标签: python


【解决方案1】:

为了让整个事情变得有意义,ask 必须由用户使用input() 提供。所以我会假设它是。以下是您的代码的修改版本。请注意,您不必正确获取案例。您可以使用字符串的lower() 方法将给出的任何答案简单地转换为小写。

ask = input('Please provide an answer..\t')
if ask.lower() == "yes":
    print("lets go, if you dont know a question you can say 'I dont know'")
    print("What is the capital of Sarajevo?")    
    ask = input('Please provide an answer..\t')
    if ask.lower() == "sarajevo":
        print("Correct, you get to move on")
    else:
        print("Sorry that isn't correct, you lost and have to leave the gameshow")
elif ask.lower() == "no":
    print("then go home")

看看它,告诉我这是否适合你。 ☺

【讨论】:

  • 这行得通,但有没有办法我可以在它下面添加更多代码?
  • 当然可以,但如果您想进行更多轮次的 QA,则不能永远嵌套 if-else 循环。您将需要某种其他类型的结构,例如 while 语句,其中问题字典作为键,答案作为值..
【解决方案2】:

我不明白你想连接哪 2 个语句 如果这对你有用,请检查:

if ask == "yes" or ask == "Yes":
    statement 1 = "lets go, if you dont know a question you can say 'I dont know' to leave the gameshow"
    print("lets go, if you dont know a question you can say 'I dont know' to leave the gameshow")
elif ask == "no" or ask == "No":
    print("then go home")
    statement 2 = "then go home"
exit(ask)

print("What is the capital of Sarajevo?")

if ask == "sarajevo" or ask == "Sarajevo":
     print("Correct, you get to move on")
     statement 3 = "Correct, you get to move on"
elif ask == "i don't know" or ask == "I don't know":
     print("Sorry that isn't correct, you lost")
     statement 4 = "Sorry that isn't correct, you lost"
 exit(ask)

statement = statement 1 + statement 3 
print statement
statement = statement 2 + statement 4
print statement 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2018-03-08
    • 2017-04-30
    相关资源
    最近更新 更多