【问题标题】:Calculating sales taxes using functions in python使用python中的函数计算销售税
【发布时间】:2017-03-13 18:09:14
【问题描述】:

我无法在 Python 3.3.5 中运行该程序,并且不确定我做错了什么。该程序 就是要求用户输入当月的总销售额,然后计算并显示 以下,县销售金额(县销售税为 2.5%)和金额 州销售税(州销售税率为 0.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()

【问题讨论】:

  • 您“无法运行此程序”?为什么不?它会抛出错误吗?如果是这样,请发布完整的错误。如所写,您的制表符和缩进是错误的,但我不知道这是否只是因为复制/粘贴到 Stack Overflow。
  • 你的函数也不返回任何东西。此外,您的 display_totals 函数正在使用仅存在于 calculate_totals 函数中的变量。您需要阅读一些关于变量作用域的内容。
  • format 和参数之间的空格。缩进(可能只是复制错误。
  • 把 display_totals() 放在 main
  • @ZWiki:不必要的空格是不好的风格(就像使用反斜杠延续一样,特别是当你已经从一个开放的括号中获得了一个免费的延续等时),但它们不会破坏任何东西.

标签: python


【解决方案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 不需要是全局的)。

【讨论】:

  • 感谢您的帮助 - 非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多