语法警告:在全局声明全局项目之前将名称“项目”分配给

时间:2018-11-28 21:39:33

标签: python-3.x

我是python的新手,正在尝试制作一个基本的购物清单程序作为开始的项目。

我在运行时遇到的错误是:

C:\ Users \ User \ PycharmProjects \ untitled \ venv \ Scripts \ python.exe C:/Users/User/.PyCharmCE2018.1/config/scratches/scratch_3.py 请输入项目编号1:C:/Users/User/.PyCharmCE2018.1/config/scratches/scratch_3.py:29:语法警告:名称“项目”在全局声明前已分配   全局项目

有人可以解释为什么我遇到此问题和/或获得相同结果的更好方法吗?

num = 1
item = input('Please enter item number ' + str(num) + ': ')
my_list = [item]
del_list = []

def _delete_ ():
    global my_list
    global del_list
    global num
    global item
    if item == 'DELETE':
        delitem = my_list.pop()
        del_list.append(delitem)
        print('You have successfully deleted ' + delitem + ' from your shopping list')
        num = num - 1

def _add_to_list_():
    global item
    global my_list
    global num
    item = input('Please enter item number ' + str(num) + ': ')
    my_list.append(item)
    num = num + 1
    print(my_list)


while item != 'STOP':
    global item
    if item == 'DELETE':
        _delete_()
    else:
        _add_to_list_()

1 个答案:

答案 0 :(得分:0)

根据Python's documentation

  

全局语句中列出的名称不得在该全局语句之前的文本代码段中使用。

     

在全局语句中列出的名称不能定义为形式参数,也不能在for循环控制目标,类定义,函数定义,导入语句或变量注释中定义。

您不应在循环内声明global item。无论如何,您已经与其中的item声明处于同一范围内,只需访问它即可。

我认为它将帮助您理解what are the rules for local and global variables in Python