Python Lis中的全局变量错误

2024-04-18 12:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个函数,它接受用户输入的四个人的名字,并将他们附加到一个列表中。但是通过下面的代码,我得到了这个用户错误。然而,当我声明一个全局变量时,我得到了一个无效的语法错误。如何修复代码?你知道吗

Traceback (most recent call last):
  File "mash.py", line 16, in <module>
    print spouse()
  File "mash.py", line 13, in spouse
    significant_other = signficant_other.append(new_spouse)
NameError: global name 'signficant_other' is not defined

这是密码。你知道吗

import random
# import random module


def spouse():
# defined function
    significant_other =[]
    #empty list
    for x in range(4):
    # for loop for an iteration of four
        new_spouse = str(raw_input("Type a person you would like to spend your life with."))
        # new spouse input
        significant_other = signficant_other.append(new_spouse)
        #significant other gets added to the list

print spouse()

谢谢你的帮助。你知道吗


Tags: 代码用户inpynewforlinefile
3条回答

更改您的线路:

significant_other = signficant_other.append(new_spouse)

对此:

significant_other.append(new_spouse)

基本上,您不能分配append方法,因为它默认返回None

>>> a = []
>>> b = a.append(5)
>>> print b
None

因此,如果您将代码更改为signficant_other.append(new_spouse),它仍然会失败,因为您输入了一个小的拼写错误,将significant拼写为signficant

有几个问题,首先:

significant_other = signficant_other.append(new_spouse)

.append()返回列表,它修改列表并返回None。你知道吗

其次,您试图使用print,但是您调用的函数没有返回您想要的,它返回None。你知道吗

此外,还有拼写问题,但以上两个问题更为重要。你知道吗

试试这个:

def spouse():

    significant_other = []

    for x in range(4):

        new_spouse = str(raw_input("...."))
        significant_other.append(new_spouse)

    return significant_other

print spouse()

你这样拼写significant_othersignficant_other

另外,你只需要做:

significant_other.append(new_spouse)

相关问题 更多 >