更新:休息外循環與前面的例子
此代碼:
# 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()
附:我只是添加了KeyError,因爲我研究了你嘗試後必須有錯誤語句。我只是一個初學者,所以我試圖自己創建程序並閱讀「絕對初學者的Python」。
UPDATE:
我固定的縮進,但現在我得到以下回溯錯誤:
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())
是因爲被定義分類彙總之前使用的定義分類彙總的其他定義(含稅總額)的定義?我嘗試將它們移動到定義的小計下方,但它仍然不起作用。
感謝您的任何建議。
最佳,
史蒂芬
匆匆一瞥,您的任何縮進都看起來不正確,這會導致問題。這*完全是*它如何看起來在你的文件? – Makoto
我更新了帖子,發現了另一個錯誤。 – Steven