需要在 if 语句中嵌套 if 语句的指导

为您提供一些背景信息,我正在做的项目是根据用户的输入创建账单,如果用户愿意在 10 天内付款,该项目的一部分概述了折扣。


我们的老师说我们必须在我们的项目中嵌套 if 语句,但我不确定为什么或如何嵌套。


我错过了嵌套课程,我不知道如何成功实现 if 语句,我在网上看到的一切都超出了我的技能水平,而且我不知道我的代码哪里出了问题。


#finding out the potential discount for paying within 10 days


if pay == "no":

    discount = 0


    if pay == "yes" and firstBill > 100 and firstBill < 200:

        discount = (firstBill * 0.015)


    elif pay == "yes" and firstBill > 200 and firstBill < 400:

        discount = (firstBill * 0.03)


    elif pay == "yes" and firstBill > 400 and firstBill < 800:

        discount = (firstBill * 0.04)


    elif  pay == "yes" and firstBill > 800:

        discount = (firstBill * 0.05)


    else:

        print("error")


else:

    print("error")


慕森王
浏览 150回答 1
1回答

慕尼黑8549860

你的意思是这样的吗?第一个if检查是否pay是"no"并跳过其余的代码。下的所有elif pay == "yes":内容仅在payis 时执行"yes"。if pay == "no":&nbsp; &nbsp; discount = 0elif pay == "yes":&nbsp; &nbsp; if 100 <= firstBill < 200:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.015)&nbsp; &nbsp; elif 200 <= firstBill < 400:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.03)&nbsp; &nbsp; elif 400 <= firstBill < 800:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.04)&nbsp; &nbsp; elif firstBill >= 800:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.05)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("error")else:&nbsp; &nbsp; print("error")顺便说一下,您可以链接比较运算符,例如x < y < z. 此外,您的代码会为 EXACTLY 200 或 EXACTLY 400 等打印“错误”。我假设这是无意的并修复了它。您还可以以不同的方式编写 if 语句:if pay == "yes":&nbsp; &nbsp; if 100 <= firstBill < 200:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.015)&nbsp; &nbsp; elif 200 <= firstBill < 400:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.03)&nbsp; &nbsp; elif 400 <= firstBill < 800:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.04)&nbsp; &nbsp; elif firstBill >= 800:&nbsp; &nbsp; &nbsp; &nbsp; discount = (firstBill * 0.05)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("error")elif pay == "no":&nbsp; &nbsp; discount = 0else:&nbsp; &nbsp; print("error")它的工作原理完全相同。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python