Python惯例新手,我的代码方向对吗?
我已经学习Python一周了,想试着做一个税率计算器。虽然还没完成,但我想知道我在Python编程方面是否走在正确的道路上。我之前只做过一点C++编程,感觉这对我现在的学习有影响(好还是不好呢?)
#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
7 个回答
2
使用4个空格来缩进代码!你可以看看这个文档,还有
import this
的输出,里面有更多信息。对我来说,这样的格式看起来不错,读起来也很简单。
5
特别是在处理财务数据时,你应该考虑使用 decimal 模块,这样可以确保你的结果没有浮点数错误。
如果你只是做一个小玩意儿来学习语言,这个问题不大,但了解这些对将来是有帮助的 :)
13
其实,有更简单的方法来处理这些数据,使用列表和配对,而不是为每个税率和限额单独设置变量。比如,看看下面的例子:
# List of (upper-limit, rate) pairs for brackets.
brackets = [ (8350, .10), (33950, .15), (82250, .25), (171550, .28), (372950, .33) ]
if __name__ == '__main__':
salary = float(raw_input("Enter your salary\n"))
accounted_for = 0 # Running total of the portion of salary already taxed
taxed = 0 # Running total of tax from portion of salary already examined
for (limit, rate) in brackets:
if salary < limit:
taxed += ( (salary - accounted_for) * rate )
accounted_for = salary
break # We've found the highest tax bracket we need to bother with
else:
taxed += ( (limit - accounted_for) * rate )
accounted_for = limit
# If we went over the max defined tax bracket, use the final rate
if accounted_for < salary:
taxed += ( (salary - accounted_for) * 0.35 )
print taxed
这里的想法是,我们不想因为有多个类似的数据项就重复写代码。所有的税率区间的工作方式都是一样的,只是税率和限额不同而已。所以我们希望把这些不同的税率和限额当作输入,放到一个标准的计算中,而不是为每个区间写一个单独的函数。