ValueError: invalid literal for int() with base 10: '1127437398.85751'

import json


# load the needed data to the list
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

#print(pop_data)
    
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = int(pop_dict['Value'])

        print(country_name + ": " + str(population))


Arab World: 357868000
Caribbean small states: 6880000
East Asia & Pacific (all income levels): 2201536674
East Asia & Pacific (developing only): 1961558757
Euro area: 331766000
Europe & Central Asia (all income levels): 890424544
Europe & Central Asia (developing only): 405204000
European Union: 502125000
Heavily indebted poor countries (HIPC): 635663000
Traceback (most recent call last):
  File "world_population.py", line 13, in <module>
    population = int(pop_dict['Value'])
ValueError: invalid literal for int() with base 10: '1127437398.85751'


# int function can not  directly deal with strings like 34423.22323,  we should  transfer the string into a float first,

# then problem solved!!! 

import json


# load the needed data to the list
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

#print(pop_data)
    
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))

        print(country_name + ": " + str(population))



猜你喜欢

转载自blog.csdn.net/fiveboots/article/details/71512306