【问题标题】:NameError: name '' is not defined - Passing function return as input to another functionNameError: name '' is not defined - 将函数返回作为输入传递给另一个函数
【发布时间】:2018-12-24 11:43:46
【问题描述】:

我试图弄清楚如何将函数的结果传递给同一脚本中的另一个函数。我已经测试了 CreateDict 函数并且它可以工作。我无法将结果用作 CreateHumanUsrNameDict 的输入 我收到以下错误是 CreateHumanUsrNameDict(UsrDict) NameError: 名称 'UsrDict' 定义

import csv
def CreateDict(filename):
    UsrDict = {}
    with open(filename) as csvfile:
        readCSV = csv.reader(csvfile, delimiter=':')
        for row in readCSV:
            UsrDict[row[0]]=row[1]
        return UsrDict


def CreateHumanUsrNameDict(UsrDict):
    HumanUsrDict={}
    for k, v in HumanUsrDict.items():
        if v == len(4):
            HumanUsrDict[k:v]
        print(HumanUsrDict)

if __name__=='__main__':
    CreateDict('Book1.csv')
    CreateHumanUsrNameDict(UsrDict)

【问题讨论】:

  • 你需要创建 UsrDict 变量:UsrDict = CreateDict('Book1.csv')
  • 您似乎对return 的工作原理有一个基本的误解。它不会导致返回的变量在调用范围内自动变为可见。您需要对返回的值进行 do 操作(例如 -- 将其分配给变量)。您的代码只是丢弃了该返回值,因此 CreateDict('Book1.csv') 完全没有效果。

标签: python python-3.x function parameter-passing nameerror


【解决方案1】:

调用 CreateDict 时需要将返回值赋给变量 UsrDict。试试这个:

import csv
def CreateDict(filename):
    UsrDict = {}
    with open(filename) as csvfile:
        readCSV = csv.reader(csvfile, delimiter=':')
        for row in readCSV:
            UsrDict[row[0]]=row[1]
        return UsrDict


def CreateHumanUsrNameDict(UsrDict):
    HumanUsrDict={}
    for k, v in HumanUsrDict.items():
        if v == len(4):
            HumanUsrDict[k:v]
        print(HumanUsrDict)

if __name__=='__main__':
    UsrDict = CreateDict('Book1.csv')
    CreateHumanUsrNameDict(UsrDict)

【讨论】:

  • 哦....谢谢。我非常感谢代码的快速响应和显示!
猜你喜欢
  • 2017-12-24
  • 2023-01-27
  • 1970-01-01
  • 2022-12-02
  • 2012-05-22
  • 2022-11-14
  • 2023-03-13
  • 2013-04-09
  • 1970-01-01
相关资源
最近更新 更多