更新:
此代码有效:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
# tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
# total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below\n")
while True:
subtotal = float(input("Enter the total price of your purchases:\t$").strip())
if subtotal == -1: break
tax = subtotal * nctaxrate
total = subtotal + tax
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
这是原始问题:
因此,我正在学习 Python,并在昨天问了一个之前的问题,并获得了一组很棒的代码,我决定对其进行修改,以使用我想要创建的 NC 销售税估算程序。
一件事是我遇到了一个我不太理解的中断循环错误。我已经搜索并试图理解其含义,但我知道代码之前有效。此外,我从头开始创建的税码程序 :) 在尝试添加在循环中提交许多输入直到用户想要“退出”之前的花哨功能之前工作。
这是代码:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below")
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
try:
subtotal = int(subtotal)
except ValueError:
print("That wasn't a number!")
try:
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
except KeyError:
print("")
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
PS我只添加了KeyError,因为我研究了你在尝试后必须有一个错误声明。我只是一个初学者,所以我正在尝试自己创建程序并阅读“Python for the Absolute Beginner”。
更新:
我修复了缩进,但现在出现以下回溯错误:
Traceback (most recent call last):
File "C:/LearningPython/taxestimator.py", line 30, in <module>
tax = subtotal * nctaxrate
NameError: name 'subtotal' is not defined
我以为我在输入中定义了它,即。
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
是因为在定义小计之前定义了使用已定义小计的其他定义(税和总计)吗?我尝试将它们移动到定义的小计之下,但它仍然无法正常工作。
感谢您的任何建议。
最好的,
史蒂文