社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Sean Xie  »  全部回复
回复总数  1
4 年前
回复了 Sean Xie 创建的主题 » 在python中绕过for循环中的ValueError

你还没有表现出你的努力,所以我不知道你到底出了什么问题。然而,在循环中放置try-except块应该可以做到:

def decade_total_count(decade, name):
    """
    sums up the number of births of the given 
    female baby `name` in a 10-year period
    
    Parameters:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    decade ... starting year of the decade
    name   ... female name 
           ... str
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    """
    count = 0
    
    for i in range(decade, decade+10):
        try:
            yearly = females[(females['name']==name) & (females['year']==i)]['births'].item()
            count = count + yearly
        except ValueError as e:
            print(f"Encountered error: {e}. Skipping.")
        
    return count