Python中跳过if语句:图书条件非‘good’时如何跳过嵌套条件逻辑
解决图书状态判断的嵌套条件跳过问题
嘿,这个需求其实很好实现,咱们分两种场景来梳理:
场景1:已输入所有信息,仅需跳过嵌套判断
你当前的代码其实已经满足「当condition不为“good”时跳过嵌套条件」的需求啦!因为外层的if condition == "good"把所有嵌套判断都包裹住了——只有当图书状态是"good"的时候,程序才会进入这个if块,执行里面关于新旧和封面的判断;如果状态不是"good",程序会直接跳过整个外层if,根本不会碰那些嵌套的if语句。
补全你未写完的代码后,完整版本是这样的:
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 low price") # 当condition不是good时,程序会直接跳过上面的嵌套if,不执行任何后续判断
场景2:想跳过后续输入步骤(更高效)
如果觉得不管状态如何都要输入图书新旧和封面类型有点冗余,咱们可以把输入age和cover的逻辑移到外层if里面。这样当状态不是"good"时,连这两个输入步骤都能直接跳过:
condition = input("What is the condition of the book? ") if condition == "good": age = input("Is the book old or new? ") cover = input("What type of cover does it have? ") 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 low price") else: # 可选:给用户一个友好提示 print("Since the book's condition isn't 'good', we can't provide a specific offer right now.")
这样调整后流程更合理:只有当图书状态符合要求时,才会继续询问细节并给出报价;不符合的话直接结束相关逻辑。
内容的提问来源于stack exchange,提问作者TheRCMKid
相关产品推荐
相关产品推荐

