【问题标题】:Returning variable outside function在函数外返回变量
【发布时间】:2015-04-23 14:24:12
【问题描述】:

为什么x没有在函数外定义? return x放错了吗?

def find(): 

x 其他:

find()

【问题讨论】:

  • 你在返回之前就已经崩溃了,如果你的条件语句评估为假,你根本就没有返回。
  • break 立即退出循环,因此它后面的语句永远不会执行。
  • 如果你没有明确return,Python会返回None

标签: python function return


【解决方案1】:

return x 放在循环之外:

def find(): 
    data=file('file.dat')
    x=0
    for line in data:
        if 'metaend' in line:
            break
        else:
            x+=1
    return x

要获取x 的值,请使用函数的返回值:

count = find()

【讨论】:

    【解决方案2】:

    你的函数永远不会返回任何东西。检查这一点,并添加一些错误处理以防止元数据检测结束

    def find(): 
        data=file('file.dat')
        x=0
        for line in data:
            if 'metaend' in line:
                return x
    
            x += 1
        raise Exception('heeey no end of metadata')
    

    顺便说一句,python 有一个非常好的函数用于循环中的计数器:

    def find(): 
        data=file('file.dat')
    
        for counter, line in enumerate(data):
            if 'metaend' in line:
                return counter
    
        raise Exception('heeey no end of metadata')
    

    【讨论】:

      猜你喜欢
      • 2013-03-27
      • 1970-01-01
      • 2013-10-09
      • 2016-02-02
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多