我正在使用 python 制作一个程序,其中涉及定义一个看起来有点像这样的函数:
def GetNumbers():
print('What is the coefficient of x^2?')
global xsqurd = int(input)
但是当我调用这个函数时,它返回一个语法错误并说'='是无效的语法。我做错什么了?
你必须这样做:
def GetNumbers():
global xsqurd
xsqurd = int(input('What is the coefficient of x^2? '))
请注意,对于 Python 2.x,您必须使用raw_input
而不是input
.
不要使用全局。这几乎总是一个糟糕的解决方案。考虑改为返回一个值。也就是说,这就是您看到该错误的原因。
global
是仅采用该关键字和名称的语句的一部分。要使用global
,您需要将其拆分。
global xsqurd
xsqurd = int(input)
当然,这假设输入是其他一些全局变量。正如克劳迪乌在下面指出的那样,您很可能打算调用input()
.
你做错了什么是写了一些无效的语法。
一条global
语句只接受一系列变量名称并将它们声明为全局的。您不能将随机的其他语法放入其中。
如果您试图声明xsqurd
为全局的,并在同一个语句中更新它,则没有办法做到这一点。只写两条语句:
global xsqurd
xsqurd = int(input)
试试这个:
xsqurd = None
def GetNumbers():
print('What is the coefficient of x^2?')
global xsqurd
xsqurd = int(22)
GetNumbers()
print xsqurd
请注意,该global xsqurd
语句位于分配之前。
其他答案很好地展示了您如何global
在所需的上下文中正确使用。如果您真的想使用全局变量,请查看这些答案。
然而,我认为这不是最 Pythonic 的解决方案,如果你的程序变得很大,它将变得难以使用。您可能想要一个更像这样的解决方案:
def GetNumbers():
val = input('What is the coefficient of x^2?')
return int(val)
def myOtherFunction(x):
return x**2 # Or whatever would be in this function
xsqurd = GetNumbers()
print xsqurd
# Using arguments to pass this to other functions
val = myOtherFunction(xsqurd)
这说明了从函数传递和返回变量,并且是执行此操作的首选方式。请注意,我已经纠正了您的一些语法错误和对输入键工作原理的误解。