Reputation:
To give you some context, the project I'm doing is creating a bill based on inputs from the user, and part of the project outlines a discount if the user would like to pay within 10 days.
Our teacher said we HAVE to nest if statements in our project but I'm not sure why or how.
I missed the nesting lesson and I have no idea how to sucsessfully implement an if statement and everything I can see online is way above my skill level, and I dont see where I'm going wrong with my code.
#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")
Upvotes: 0
Views: 68
Reputation: 16573
Do you mean something like this? The first if
checks if pay
is "no"
and skips the rest of the code. Everything under elif pay == "yes":
will only execute if pay
is "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")
By the way, you can chain comparison operators like x < y < z
. Also, your code prints "error" for EXACTLY 200 or EXACTLY 400 and so on. I'm assuming that was unintended and fixed that.
You can also write the if statements differently:
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")
And it will work exactly the same.
Upvotes: 2