为什么 Python 向我返回一条错误消息,说我错误地使用了 int()

Why is Python returning an error message to me saying something like that I used a int() wrongly

这是我的代码:

def PopDensity(population, area):
    PopulationDensity = (population/area)
    return PopulationDensity
state= "Maryland"
population='6,052,000'
area="12,407"
PopDensity(int(population), int(area))
stat="The population density of %s is %s."
print(stat % (state,PopulationDensity))

Python 一直在上面的打印函数中返回错误给我。它看起来像这样:

Traceback (most recent call last): File "C:/Users/adamn/OneDrive/Desktop/.py files/Assignment5_1astrub1359960.py", line 8, in PopDensity(int(population), int(area)) ValueError: invalid literal for int() with base 10: '6,052,000'"

谁能告诉我我在打印功能上做错了什么,并提出改进建议。我查看了另一个 google 就此向我推荐的问题,但它并没有真正帮助。

问题在于您传递给 int() 的数字格式。您可以直接初始化整数,例如population = 6052000。您使用的是字符串而不是整数。相应地更正您的代码会产生

def population_density(population, area):
    pop_density = (population/area)
    return pop_density
state= "Maryland"
population = 6052000
area = 12407
computed_density = population_density(population, area)
stat="The population density of %s is %s."
print(stat % (state,computed_density))