List作为函数参数返回NameError:未定义

时间:2018-03-20 06:32:48

标签: python python-2.7

我是Python新手。与班级<script> var val= <?php echo $val; ?> </script> 合作 老师设置了一个项目,我们在其中编写一个程序,该程序接受一个Monty Python脚本(由用户输入),将其存储在列表列表中,用脚本替换脚本中的特定名称。命名并将修改后的脚本打印到控制台。

我遇到的问题是我的第三个函数2.7replace_name

然而,我正在

  

NameError:&#39; WORD_LIST&#39;未定义

据我所知,如果未在Main中定义变量,则它的功能是本地的 我想,通过在函数中使用return来存储该信息以供后续函数使用。

我错了吗?

parameters are the list of lists, old name, new name

如果我的缩进有点偏离,我道歉 我试图通过复制/粘贴来纠正它 repl.it中没有给出缩进错误。

def new_name(): #prompts for user's name. checks if input is valid
  while True:
    name = raw_input("Please enter your name.\n")
    if len(name) < 1:
      print "Invalid, please enter your name.\n"
    else:
      return name

def orig_script():#reads in script, splits into list of lists
  word_list = [] 
  script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n")
  if len(script) < 1:
      print "Empty text field. Please try again.\n"
  while script != 'done':#splits string input,adds to list
    words = script.split()
    word_list.append(words)
    script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ")
    if len(script) < 1:
      print "Empty text field. Please try again.\n"
  return word_list

def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes.
  new_list = []
  for sentences in range(word_list):
    sentence = word_list[sentences]
    for words in range(sentece):
      word = sentence[words]
      if word == old_name:
        sentence[words] == new_name
        new_list.append(sentence)
   print new_list#debugging-change to return

new_name()
orig_script()
replace_name(word_list, Robin, new_name)

2 个答案:

答案 0 :(得分:1)

您没有分配任何word_list, Robin, new_name个变量。返回特定名称的变量不会将其自身绑定到任何类型的外部变量,尤其是不能使用相同名称的变量。

例如,您需要将返回值明确指定给自己的变量。

word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name) 

另外

for sentences in range(len(word_list)):
    sentence = word_list[sentences]

相同
for sentence in word_list:

注意:sentece确实存在拼写错误,这是比较,而不是作业sentence[words] == new_name

奖金,我认为你可以将replace_name重写为

def replace_name(word_list,old_name,new_name):
    return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]

答案 1 :(得分:0)

在函数参数中传递参数。

实施例

#take the o/p of variable in another one and pass in funcation
return_val = orig_script()

old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]

#calling replace name funcation 
replace_name(return_val,old_name,new_name)