gpt4 book ai didi

python - python 约定的新手,我的代码是否在正确的轨道上?

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:57 25 4
gpt4 key购买 nike

我已经阅读了一周有关 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

最佳答案

对于每个括号的限制和比率,可能有一种更有效的方法来使用列表和对而不是单独的变量来执行此操作。例如,请考虑以下内容:

# 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

我们的想法是,我们不想重复我们不必重复的代码,只是因为我们有多项相似的数据要处理。除了不同的税率和限制外,税级的功能都相同,因此我们希望它们作为标准计算的输入,而不是它们各自的功能。

关于python - python 约定的新手,我的代码是否在正确的轨道上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1216395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com