我认为if-elif-else语句有问题,因为它总是转到其他地方
#initialize total
total=0.0
#ask for inputs
budget=float(input("Plz Enter amount that you budgeted for a month: "))
expense=float(input("Plz Enter 1st expense - to quit enter 0: "))
while expense!=0:
# Add the expense to the accumulator.
total += expense
expense=float(input("Plz Enter a expense - to quit enter 0: "))
#display results
if total>budget:
print("You are over-budget by",total-budget)
elif budget<total:
print("You have",budget-total,"to spare")
else:
print("Your budget is equal to expense")
答案 0 :(得分:10)
if
和elif
都在做同样的事情
if total>budget:
print("You are over-budget by",total-budget)
elif budget<total:
print("You have",budget-total,"to spare")
应该是:
if total>budget:
print("You are over-budget by",total-budget)
elif budget>total:
print("You have",budget-total,"to spare")
但是,为了更清洁(你会发现错误更容易):
if total>budget:
print("You are over-budget by",total-budget)
elif total<budget:
print("You have",budget-total,"to spare")
了解总计现在是如何对齐的?更容易看出操作员方向的差异。不需要思考。
答案 1 :(得分:2)
我建议,当对同一组变量执行if / elif时,始终保持顺序相同,这样可以提高可读性,并且更适合错误检查。你的大脑会进行一次艰难的上下文切换,以便了解它们的顺序是否相同,但标志是相同的,这是非直观的。
你的if / elif / else应该如下:
if total > budget:
print("You are over-budget by",total-budget)
elif total < budget:
print("You have",budget-total,"to spare")
else:
print("Your budget is equal to expense")