"unsupported operand types(s)"错误消息



获取捐赠信息并对其进行处理以生成报告。

def percent_of_target(donation, goal):
"""returns a float representing the percentage of the overall goal that 
is contributed by the given donation"""
result = donation / goal
result_percentage = result * 100
return result_percentage
def categorise_donations(donations, campaign_goal):
"""return a list of tuples with the first value of the tuple being the 
amount donated and the second value being the category for that donation"""
my_list = []
for donation in donations:
percentage = percent_of_target(donation, campaign_goal)
# append to list and continue
return my_list
def main():
"""Gets information from the user and then prints a report using functions
that you have written through this quiz"""
input_donations = []
goal_amount = input('Campaign goal: ')
print('Enter the donations received.')
continue_program = True
while continue_program == True:
donation = input('Amount donated? ')
if donation.isalpha() == True:
if donation.lower() == 'q':
continue_program = False
else:
input_donations.append(donation)
donations = categorise_donations(input_donations, goal_amount)
# print the table and exit
main()

外壳中的输出:

Python 3.8.4 (v3.8.4:dfa645a65e, Jul 13 2020, 10:45:06) 
[Clang 6.0 (clang-600.0.57)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate Ass2(q6).py]
Campaign goal: 1000.00
Enter the donations received.
Amount donated? 10.00
Amount donated? 100.00
Amount donated? 1001.00
Amount donated? Q
Traceback (most recent call last):
File "/Users/oscarevans/Library/Mobile Documents/com~apple~CloudDocs/Documents/Ass2(q6).py", line 102, in <module>
main()
File "/Users/oscarevans/Library/Mobile Documents/com~apple~CloudDocs/Documents/Ass2(q6).py", line 98, in <module>
donations = categorise_donations(input_donations, goal_amount)
File "/Users/oscarevans/Library/Mobile Documents/com~apple~CloudDocs/Documents/Ass2(q6).py", line 50, in <module>
percentage = percent_of_target(donation, campaign_goal)
File "/Users/oscarevans/Library/Mobile Documents/com~apple~CloudDocs/Documents/Ass2(q6).py", line 41, in <module>
result = donation / goal
builtins.TypeError: unsupported operand type(s) for /: 'str' and 'str'

注:

  • 当输入"Q"或"Q"作为"捐赠"的输入时,该函数旨在退出while循环并停止接受捐赠;捐赠金额">

  • 该程序旨在打印一张输入捐赠价值和捐赠金额类别的表格。

您的捐赠值(和目标(都是字符串。一旦您确定没有看到告诉您提前退出的'q'输入,您可能应该立即将它们转换为数字数据类型。

试试这样的东西:

goal_amount = float(input('Campaign goal: '))    # convert to float
print('Enter the donations received.')
continue_program = True
while continue_program == True:
donation = input('Amount donated? ')
if donation.isalpha() == True:
if donation.lower() == 'q':
continue_program = False
else:
input_donations.append(float(donation))  # here too

相关内容

最新更新