亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

需要在 if 語句中嵌套 if 語句的指導

需要在 if 語句中嵌套 if 語句的指導

慕森王 2021-09-11 13:24:51
為您提供一些背景信息,我正在做的項目是根據用戶的輸入創建賬單,如果用戶愿意在 10 天內付款,該項目的一部分概述了折扣。我們的老師說我們必須在我們的項目中嵌套 if 語句,但我不確定為什么或如何嵌套。我錯過了嵌套課程,我不知道如何成功實現 if 語句,我在網上看到的一切都超出了我的技能水平,而且我不知道我的代碼哪里出了問題。#finding out the potential discount for paying within 10 daysif 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")
查看完整描述

1 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

你的意思是這樣的嗎?第一個if檢查是否pay是"no"并跳過其余的代碼。下的所有elif pay == "yes":內容僅在payis 時執行"yes"。


if pay == "no":

    discount = 0

elif pay == "yes":

    if 100 <= firstBill < 200:

        discount = (firstBill * 0.015)

    elif 200 <= firstBill < 400:

        discount = (firstBill * 0.03)

    elif 400 <= firstBill < 800:

        discount = (firstBill * 0.04)

    elif firstBill >= 800:

        discount = (firstBill * 0.05)

    else:

        print("error")

else:

    print("error")

順便說一下,您可以鏈接比較運算符,例如x < y < z. 此外,您的代碼會為 EXACTLY 200 或 EXACTLY 400 等打印“錯誤”。我假設這是無意的并修復了它。


您還可以以不同的方式編寫 if 語句:


if pay == "yes":

    if 100 <= firstBill < 200:

        discount = (firstBill * 0.015)

    elif 200 <= firstBill < 400:

        discount = (firstBill * 0.03)

    elif 400 <= firstBill < 800:

        discount = (firstBill * 0.04)

    elif firstBill >= 800:

        discount = (firstBill * 0.05)

    else:

        print("error")

elif pay == "no":

    discount = 0

else:

    print("error")

它的工作原理完全相同。


查看完整回答
反對 回復 2021-09-11
  • 1 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號