Tradeback错误和NameError python

时间:2017-05-02 15:51:34

标签: python nameerror traceback

我尝试输入1-9之间的值,然后打印用户输入的数字的单词版本。我不断收到回溯错误并命名错误:

  Traceback (most recent call last):
  File "/Users/Michell/Desktop/testq1.1.py", line 13, in <module>
    main()
  File "/Users/Michell/Desktop/testq1.1.py", line 11, in main
    print (fun(num))
  File "/Users/Michell/Desktop/testq1.1.py", line 3, in fun
    word2num = numlist[num-1]
NameError: name 'numlist' is not defined* 

我的代码如下:

def fun(num):

      word2num = numlist[num-1]
      return numlist
      return num

def main():

      num = eval(input("Enter a # between 1-9: "))
      numlist = ["one","two","three","four","five","six","seven","eight","nine"]
      print (fun(num))

main()

1 个答案:

答案 0 :(得分:2)

您需要将numlist传递给fun函数并返回word2num而不是整个列表:

def fun(num, numlist):
    word2num = numlist[num - 1]
    return word2num

def main():
    num = int(input("Enter a # between 1-9: "))
    numlist = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]

    print(fun(num, numlist))

main()