【问题标题】:Skipping if statments in Python在 Python 中跳过 if 语句
【发布时间】:2018-04-22 11:15:45
【问题描述】:

我在我的代码行中创建了嵌套条件,但如果任何其他“(书)条件”条件不是“好”,我想跳过它们。

condition = input("What is the condition of the book? ")
age = input("Is the book old or new? ")
cover = input("What type of cover does it have? ")


if condition == "good":
    if age == "new":
        if cover == "hardcover":
            print("We can offer you a high price")
        elif cover == "papercover":
            print("We can offer you a medium price")
    elif age == "old":
        print("We can offer you a medium price")
elif condition == "poor":
    print("We can offer a low price")
elif condition == "terrible":
    print("Sorry we cannot accept this book")
else:
    print("I do not understand, please leave the store")

【问题讨论】:

  • “跳过它们”是什么意思?你能用特定的输入展示你想要发生的事情吗?
  • 对于第一个语句,如果我输入“好”,它将按照我想要的方式通过另一个语句。但是如果输入'poor',那么我将继续执行其他语句。如果我输入“可怕”或“差”,我基本上想跳过“年龄”和“封面”陈述
  • 如果您不输入'good',您将跳过年龄并覆盖内容......它们仅在'good'书籍中执行。我不明白你
  • 如果我填写“差”或“糟糕”,即使我不想这样做,我仍然必须填写“年龄”和“封面”声明。

标签: python python-3.x if-statement nested


【解决方案1】:

您需要将您的输入移动到 if 语句中,这样您就可以使用已经存在的 if-else 结构,如下所示:

condition = input("What is the condition of the book? ")

if condition == "good":
    age = input("Is the book old or new? ")
    if age == "new":
        cover = input("What type of cover does it have? ")
        if cover == "hardcover":
            print("We can offer you a high price")
        elif cover == "papercover":
            print("We can offer you a medium price")
    elif age == "old":
        print("We can offer you a medium price")
elif condition == "poor":
    print("We can offer a low price")
elif condition == "terrible":
    print("Sorry we cannot accept this book")
else:
    print("I do not understand, please leave the store")

【讨论】:

  • 如果此答案正确,请考虑将其标记为这样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
相关资源
最近更新 更多