首页 > 解决方案 > 如何修复 NameError:运行 python 脚本时未定义名称“作者”

问题描述

我正在尝试在我的 Mac 上的终端上打开它,但是当它明确定义时,我不断收到未定义的名称“作者”。

def bibformat_mla(author, title, city, publisher, year):
    author = input("enter author: ")
    title = input("enter title: ")
    city = input("enter city: ")
    publisher = input("enter publisher: ")
    year = input("enter year: ")
    answer = author + ' , ' + title + ' , ' + city + ': ' + publisher + ', ' + year
    return answer


bibformat_mla(author, title, city, publisher, year)
'author, title, city: publisher, year'

bibformat_mla("Jake, Matt", "Open Data ", "Winnipeg", "AU Press", 2013)
 'Morin, Pat. Open Data Structures. Winnipeg: AU Press, 2013'

标签: pythonpython-3.x

解决方案


当您运行以下命令时:

bibformat_mla(author,title,city,publisher,year)

你对程序说你有一个名为“author”的变量,它可以传递给 biblformat()。这会导致错误,因为在调用函数之前未定义变量。

即你告诉函数期待某个变量,它会向你抛出一个错误,因为该变量实际上还不存在。

从你想要完成的样子来看,你可以像这样简单地调用函数:

bibformat_mla()

您还需要将定义更改为此,以便您的函数不再需要参数:

def bibformat_mla():

推荐阅读