使用python中的函数计算销售税

时间:2014-09-23 18:11:15

标签: python

我无法在Python 3.3.5中运行此程序并且不确定我做错了什么。该程序 是要求用户输入当月的总销售额,然后计算并显示 以下,县销售金额(县销售税为2.5%)和金额 州销售税(州销售税率为.05)和销售税总额(县和州) 我复制并粘贴了迄今为止我所做的事情。

# Show individually the 5 purchases amounts, compute the state and county sales
# tax on those combined  purchases and calculate the total of taxes
# and purchases
county_sales_tax =  .025 
state_sales_tax = .05

# Enter the purchase price
def main():
  purchase = float(input('Enter the price of the purchase: '))
  calculate_totals(purchase)

# Calculate the purchase price with the coounty and state sales tax
def calculate_totals(purchase):
  county_sales_tax = purchase * .025 
  state_sales_tax = purchase * .05
  total_sales_tax = county_sales_tax + state_sales_tax
  total_price = purchase + state_sales_tax + county_sales_tax


# display the amount of the purchases, county and state sales
# taxes, combined amount of the both taxes and total sale with taxes
def display_totals(purchase, state_sales_tax, county_sales_tax, total_taxes, total_price):
  print('The purchase price is $, ')
  print('The county_sales_tax is $', \
    format (county_sales_tax, '.2f'))
  print('The state_sales_tax is $', \
    format (state_sales_tax, '.2f'))
  print('The total_sales_tax is $:, ')
  print('The total_price is $:, ')

# Call the main function
main()

1 个答案:

答案 0 :(得分:1)

我修了几件事,我会试着去处理一些错误。

def calculateStateTax(price):
    state_sales_tax = .05
    return price * state_sales_tax

def calculateCountyTax(price):
    county_sales_tax =  .025
    return price * county_sales_tax

def displayTotals(price):
    print('Original price', price)
    state_tax = calculateStateTax(price)
    print('State tax', state_tax)
    county_tax = calculateCountyTax(price)
    print('County tax', county_tax)
    print('Total', price + state_tax + county_tax)

def main():
    price = float(input('Enter the price of the purchase: '))
    displayTotals(price)
  1. 缩进在Python中非常重要!缩进用于定义事物的范围,请注意定义函数中的所有代码都是选项卡(或4个空格)

  2. 通常,您可以使用函数输入参数和返回值来传递内容,而不是声明全局变量。

  3. 请注意,displayTotals函数会调用其他函数,并通过return从中获取值。这意味着displayTotals并不需要传递所有这些参数。

  4. 通常最好只在需要存在的范围内定义常量(例如state_sales_tax不需要是全局的)。