-1

我正在使用 python 制作一个程序,其中涉及定义一个看起来有点像这样的函数:

def GetNumbers(): 

print('What is the coefficient of x^2?')
global xsqurd = int(input)

但是当我调用这个函数时,它返回一个语法错误并说'='是无效的语法。我做错什么了?

4

5 回答 5

1

你必须这样做:

def GetNumbers():
    global xsqurd
    xsqurd = int(input('What is the coefficient of x^2? '))

请注意,对于 Python 2.x,您必须使用raw_input而不是input.

于 2013-10-03T23:16:09.983 回答
0

不要使用全局。这几乎总是一个糟糕的解决方案。考虑改为返回一个值。也就是说,这就是您看到该错误的原因。

global是仅采用该关键字和名称的语句的一部分。要使用global,您需要将其拆分。

global xsqurd
xsqurd = int(input)

当然,这假设输入是其他一些全局变量。正如克劳迪乌在下面指出的那样,您很可能打算调用input().

于 2013-10-03T23:18:03.117 回答
0

你做错了什么是写了一些无效的语法。

一条global语句只接受一系列变量名称并将它们声明为全局的。您不能将随机的其他语法放入其中。

如果您试图声明xsqurd为全局的,并在同一个语句中更新它,则没有办法做到这一点。只写两条语句:

global xsqurd
xsqurd = int(input)
于 2013-10-03T23:18:16.780 回答
0

试试这个:

xsqurd = None
def GetNumbers(): 
    print('What is the coefficient of x^2?')
    global xsqurd
    xsqurd = int(22)

GetNumbers()
print xsqurd

请注意,该global xsqurd语句位于分配之前。

于 2013-10-03T23:20:55.583 回答
0

其他答案很好地展示了您如何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)

这说明了从函数传递和返回变量,并且是执行此操作的首选方式。请注意,我已经纠正了您的一些语法错误和对输入键工作原理的误解。

于 2013-10-03T23:32:47.633 回答