如何修复NameError:运行python脚本时未定义名称'author'

时间:2019-01-10 22:59:02

标签: python python-3.x

我正在尝试在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'

3 个答案:

答案 0 :(得分:3)

运行以下命令时:

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

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

即,您要告诉该函数期望某个变量,并且由于该变量实际上尚不存在,它会向您抛出错误。

从您想要完成的工作看起来,您可以像这样简单地调用函数:

bibformat_mla()

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

def bibformat_mla():

答案 1 :(得分:0)

您需要确定函数是将这些字符串作为参数接受还是会提示用户输入这些字符串?没什么要求用户提供值作为参数,然后立即用输入的值覆盖它们。

所以您可以选择。

  1. 在调用函数之前执行输入,并将输入的值传递给函数。
  2. 删除该函数的参数,并允许用户输入字符串作为bibformat_mla的一部分。

代码:

def bibformat_mla1 (author,title,city,publisher,year):
    return author + ' , ' + title + ' , ' + city + ': ' + publisher + ', ' + str(year)

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

print(bibformat_mla1("Jake, Matt", "Open Data ", "Winnipeg", "AU Press", 2013))
print(bibformat_mla2())

答案 2 :(得分:0)

对于函数,您可以将信息作为参数传递,在函数定义中,您表示运行该函数时还将传递5个变量。

从外观上看,您是通过用户输入来设置变量的,因此您不需要传递参数,删除它们应该可使代码正常工作。

此:

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

对此:

def bibformat_mla():