[英]Defining lists and calling functions in Python
我正在使用Python3。這是一個班級的家庭作業項目,但我沒有尋找任何可以解決我問題的方法! 我只是想知道是否有人可以幫助指出我哪里出了問題,或者我需要研究什么才能使我的代碼正常工作。
def main():
taxPayersList = []
incomesList = []
taxesList = []
taxPayersList, incomesList = inputNamesAndIncomes(taxPayersList, incomesList)
taxesList = calculateTaxes(incomesList)
displayTaxReport(taxesList, incomesList, taxPayersList)
def inputNamesAndIncomes(taxPayersList, incomesList):
print('Welcome to Xanadu Tax Computation Program')
print('')
confirmation = input('Do you have income amounts? y/n ')
index = 0
try:
while confirmation == 'y' or confirmation == 'Y':
taxPayersList[index] = input('Enter a tax payer name: ')
incomesList[index] = float(input('Enter income amount: '))
confirmation = input('Are there more income amounts? ')
index += 1
except:
print('An error occurred. Please only enter numbers for income amount.')
return taxPayersList, incomesList
def calculateTaxes(incomesList):
index = len(incomesList)
while index < len(incomesList):
if incomesList[index] >= 0 and incomesList[index] <= 50000:
taxesList[index] = incomesList[index] * .05
elif incomesList[index] >= 50000 and incomesList[index] <= 100000:
taxesList[index] = 2500 + ((incomesList[index] - 50000) * .07)
elif incomesList[index] >= 100000:
taxesList[index] = 6000 + ((incomesList[index] - 100000) * .09)
index += 1
return incomesList
def displayTaxReport(taxesList, incomesList, taxPayersList):
print('2018 TAX DUES FOR XANADU STATE')
print('')
print('Name\t\tANNUAL INCOME\tTAXDUE')
for n in incomesList:
print(taxPayersList,'\t\t',incomesList,'\t',taxesList)
main()
現在,我可以在第一個輸入中輸入名稱,但是一旦按下Enter鍵,它就會打印出我的錯誤代碼,然后打印出如下所示的最終功能。
Welcome to Xanadu Tax Computation Program
Do you have income amounts? y/n y
Enter a taxpayer name: Susan
An error occurred. Please only enter numbers for income amount.
2018 TAX DUES FOR XANADU STATE
Name ANNUAL INCOME TAXDUE
我知道這是一團糟,但是任何幫助都將不勝感激!
您不能只是為列表添加一個不存在的索引以向其中添加項目:
>>> a = []
>>> a[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
相反,您應該查看對列表使用.append()
方法。
(之所以看不到IndexError
調試詳細信息,是因為您的except
子句阻止了它的顯示。裸except
子句通常被認為是反模式,因為它們掩蓋了此類意外錯誤,並且更難於指出出了什么問題-他們抓住了任何異常,不僅是由於用戶輸入錯誤而引起的異常。)
有一個IndexError: list assignment index out of range
該行的IndexError: list assignment index out of range
taxPayersList[index] = input('Enter a tax payer name: ')
您沒有看到它是因為您排除了所有錯誤並且沒有打印出來。 我建議使用
name = input('Enter a tax payer name:')
taxPayersList.append(name)
等等。請注意,我將其附加到列表中。 我還建議使用其他錯誤處理策略。
另外,您可能希望使用詞典而不是兩個列表,因為您希望將收入與姓名相關聯,
name = input('Enter a tax payer name:')
income = float(input('Enter income amount:'))
incomes[name] = income
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.