2016-08-02 75 views
2

我对Python很新,我正在阅读一本初学者书籍。代码不是用英文写的,所以我尽力翻译,希望你们明白。 它具有这样的演习,我们从用户的工资计算税:我不明白这是如何工作的(功能?)

salary = float(input("Enter your salary to taxes calculation: ")) 
base = salary 
taxes = 0 

if base > 3000: 
    taxes = taxes + ((base - 3000) * 0.35) 
    base = 3000 
if base > 1000: 
    taxes = taxes + ((base - 1000) * 0.20) 

我的问题是,当输入比3000更大,例如,如果我的5000薪酬运行的代码,结果会为1100.但是,当我在计算器上做'相同'的数学结果是700,所以我迷失在这里,有人能解释一下吗?

+0

是你在上面显示的所有代码吗? – MaxZoom

+0

您的计算器是否支持括号,并且您是否使用它们? – user2357112

+0

是的,它只是有一个打印的声明到底显示的工资和税收 – Zetto

回答

3

好吧,让我们走过它,因为它的5000

salary = float(input("Enter your salary to taxes calculation: ")) 
base = salary 
# base = 5000 
taxes = 0 

if base > 3000: # base is larger than 3000, so we enter the if statement 
    taxes = taxes + ((base - 3000) * 0.35) 
    # taxes = 0 + ((5000 - 3000) * 0.35) 
    # taxes = 0 + 700 
    # taxes = 700 
    base = 3000 # base is set to 3000 
if base > 1000: # base was set to 3000 in the line above, so we enter the if statement 
    taxes = taxes + ((base - 1000) * 0.20) 
    # taxes = 700 + ((3000 - 1000) * 0.20), remember taxes is already 700 from above 
    # taxes = 700 + 400 
    # taxes = 1100 

例子是两个if语句,而不是ifelse我们在base设置为大于3000时评估两个语句。我希望有所帮助。

5

请注意,在工资5000的情况下,控件将转到if语句。所以它从第一个出来,从第二个到400,因此答案是700 + 400。这也是有道理的,因为税收计算大部分被分割在括号内,并且不是薪水的平坦百分比。

1

它流动到第二功能

,所以如果我在数子:

Salary = 5000 
base = 5000 
taxes = 0 

if 5000 > 3000: 
    taxes = 0 + ((5000- 3000) * 0.35) # = 700 
    base = 3000 
if 3000 > 1000: 
    taxes = 700 + ((3000 - 1000) * 0.20) # = 1100 
0

这是一个经济的方程式,可以计算每个工资部分的税额。 过程会是这样:

  • 对于量大于3000计算35%的税薪金的这一部分。
  • 对于大于1000(且小于3000)的金额,计算此部分工资的20%的税率。

薪水税将是这些税的总和。