更新时间:
此代码起作用:
# 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销售税估计器程序一起工作。在
一件事是我得到了一个中断循环错误,我不太明白。我已经搜索并试图理解其含义,但我知道代码以前起作用了。另外,我从头开始创建的税码程序:)在尝试添加在一个循环中提交许多输入的奇特功能之前工作,直到用户想要“退出”。在
代码如下:
^{pr2}$另外,我只添加了KeyError,因为我研究过你在尝试之后必须有一个错误语句。我只是一个初学者,所以我试图自己创建程序,并阅读“Python for the Absolute初学者”。在
更新:
我修复了缩进,但现在我得到了以下回溯错误:
Traceback (most recent call last):
File "C:/LearningPython/taxestimator.py", line 30, in <module>
tax = subtotal * nctaxrate
NameError: name 'subtotal' is not defined
我想我是在输入ie中定义的
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
是不是因为使用定义的小计的其他定义(税和总额)在定义小计之前定义?我试着把它们移到定义的小计下面,但还是没用。在
谢谢你的建议。在
最好的
史蒂文
可能需要缩进。。。除非这只是输入问题时的一个错误
您面临的主要问题是Python需要空白来限定方法的范围。否则,语句将无法按预期运行,例如:
不会用有效的输入跳出循环(如果你把一个字符串放在那里,那就另当别论了)。另外,如果所有内容都在
main()
的范围内,那么每个语句都需要一个缩进级别(或者四行空格,如果您愿意的话)。现在,您的while
不会在main()
的范围内运行。在另外,在实际给它一个值之前,先引用
subtotal
。由于subtotal
没有正确初始化,您将没有用于它的值。在您需要重写代码,使}在您定义
^{pr2}$tax
和{subtotal
之后由定义。在最后,如果}被正确定义(在上面的后面,它们将被定义),那么当您希望打印出这些值时,就不需要使用superflous
subtotal
、total
、和{try...except
语句。在相关问题 更多 >
编程相关推荐