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

2024-09-27 09:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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总是在上面的print函数中向我返回错误的内容。看起来是这样的:

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'"

请告诉我打印功能有什么问题,并提出改进建议。我看了另一个谷歌向我提出的问题,但它并没有真正起到帮助作用


Tags: the代码pyreturndefareadensitystat
1条回答
网友
1楼 · 发布于 2024-09-27 09:24:15

问题在于传递给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))

相关问题 更多 >

    热门问题