2013-11-21 248 views
2

我该如何去做一个范围70000以上的for-loop?我正在做一个所得税的for-loop,当收入超过70000时,有30%的税。我会做一些像for income in range(income-70000)所得税计算蟒蛇

那么,起初我开发了一个代码,没有使用循环,它工作得很好,但后来我被告知我需要在我的代码中加入一个循环。这就是我所拥有的,但对我来说使用for循环没有任何意义。有人能帮我吗?

def tax(income):

for income in range(10001): 
    tax = 0 
    for income in range(10002,30001): 
     tax = income*(0.1) + tax 
     for income in range(30002,70001): 
      tax = income*(0.2) + tax 
      for income in range(70002,100000): 
       tax = income*(0.3) + tax 
print (tax) 

好了,现在我已经尝试使用while循环,但它并没有返回值。告诉我你的想法。我需要根据收入来计算所得税。第一万美元没有税。接下来的20000有10%。接下来的40000有20%。 70000以上是30%。

def taxes(income):

income >= 0 
while True: 
    if income < 10000: 
     tax = 0 
    elif income > 10000 and income <= 30000: 
     tax = (income-10000)*(0.1) 
    elif income > 30000 and income <= 70000: 
     tax = (income-30000)*(0.2) + 2000 
    elif income > 70000: 
     tax = (income - 70000)*(0.3) + 10000 
return tax 
+0

你能解释一下你在做什么吗?你在建立税表吗? for循环内发生了什么?之前/之后会发生什么? – selllikesybok

+2

所得税?你需要什么循环?乘。 – shx2

+6

为什么不只是'如果收入> = 7000'?这听起来像是你试图将英文指令“7000以上的收入,征收30%的税”转化为Python,但实际上“确实”会给你带来什么惊喜。 – Kevin

回答

9

问:我如何去制作一个for循环,射程70000以上?

答:使用itertools.count()方法:

import itertools 

for amount in itertools.count(70000): 
    print(amount * 0.30) 

问:我需要计算基础上的收入所得税。第一万美元没有税。接下来的20000有10%。接下来的40000有20%。 70000以上是30%。

答:bisect module是伟大的,在范围内做查找:

from bisect import bisect 

rates = [0, 10, 20, 30] # 10% 20% 30% 

brackets = [10000,  # first 10,000 
      30000,  # next 20,000 
      70000]  # next 40,000 

base_tax = [0,   # 10,000 * 0% 
      2000,   # 20,000 * 10% 
      10000]  # 40,000 * 20% + 2,000 

def tax(income): 
    i = bisect(brackets, income) 
    if not i: 
     return 0 
    rate = rates[i] 
    bracket = brackets[i-1] 
    income_in_bracket = income - bracket 
    tax_in_bracket = income_in_bracket * rate/100 
    total_tax = base_tax[i-1] + tax_in_bracket 
    return total_tax 
1

如果你真的必须循环,一个办法是加了税分别收入各单位:

def calculate_tax(income): 
    tax = 0 
    brackets = {(10000,30000):0.1, ...} 
    for bracket in brackets: 
     if income > bracket[0]: 
      for _ in range(bracket[0], min(income, bracket[1])): 
       tax += brackets[bracket] 
    return tax 
1

这两个你的函数肯定是不是计算需要的值。你需要这样的东西:

import sys 

income = 100000 
taxes = [(10000, 0), (20000, 0.1), (40000, 0.2), (sys.maxint, 0.3)] 

billed_tax = 0 
for amount, tax in taxes: 
    billed_amount = min(income, amount) 
    billed_tax += billed_amount*tax 
    income -= billed_amount 
    if income <= 0: 
     break 

>>> billed_tax 
19000.0 
+0

这个答案不正确。考虑循环的第二次迭代。金额是20000,收入是900000.所以billed_amount是20000.所以税额= .1适用于20000.但是,这个税只适用于20000到10000之间的数量,也就是10000.并且看着输入,你可以看看这个例子19000的税率太高,因为60000应该征税.2,但其他税率应该低于这个税率,结果应该低于19%。 – garyrob

+0

@garyrob你错了。如果你重读这个问题,10,20和40是递增的而不是实际的步骤。计算步长之外的增量是显而易见的,并且是这种考虑的OOS。 – alko

-1

我不知道任何蟒蛇,但你的问题不是语言要么。你需要阅读有关条件。你不需要所有这些,只需要1,然后按照你的规则进行IFS。