Python 如何使用函数下面定义的变量?

Python 如何使用函数下面定义的变量?,python,class,python-3.x,Python,Class,Python 3.x,我试图使用类制作一个计算器,但得到的错误是“变量未定义” 我正在尝试的是(我的代码中有更多的函数,但相关的代码是) 我得到的是“变量不只是定义的” 我正在使用Windows7和Python 3.3。可能的问题是什么?在Start()函数中,将 global Action 这样,变量将进入全局范围,因此它将从其他函数可见 然而,这不是一种好的风格。相反,您应该将参数传递给其他函数,而不是依赖全局变量。您必须明确地将“变量”传递给需要它们的函数。您可以在任何编程教程(从Python的官方教程开始)

我试图使用类制作一个计算器,但得到的错误是“变量未定义”

我正在尝试的是(我的代码中有更多的函数,但相关的代码是)

我得到的是“变量不只是定义的” 我正在使用Windows7和Python 3.3。可能的问题是什么?

Start()
函数中,将

global Action
这样,变量将进入全局范围,因此它将从其他函数可见


然而,这不是一种好的风格。相反,您应该将参数传递给其他函数,而不是依赖全局变量。

您必须明确地将“变量”传递给需要它们的函数。您可以在任何编程教程(从Python的官方教程开始)中阅读更多关于这方面的内容。要从设置变量的函数中“获取”变量,必须
返回
变量。这真的是CS101顺便说一句

例如:

def foo(arg1, arg2):
   print arg1, arg2

def bar():
   y = raw_input("y please")
   return y

what = "Hello"
whatelse = bar()
foo(what, whatelse)
更多信息请点击此处:

您的脚本的固定版本(nb在Python2.7上测试,带有
input
,但应在3.x上正常工作):


哪一个变量的用法还没有定义?对于这个问题,人们投了反对票:有一天我们都是新手,至少op尝试了一些东西。请保留对那些要求对其分配的现成答案的人的反对票。全局变量不是一个好主意。它打破了模块化的概念。我会确保你传递了你想要使用的变量。我真的不认为你应该再次调用那个变量但是如果你想,将其设置为全局并不是最好的方法。有人能举个例子说明您将如何执行此操作吗?在名称之前添加
global
不会使名称从其他函数中可见。因此,如果我想向Cal添加更多fuctinons,我所要做的就是放置def cube(self,number):启动它。
def(…)
定义一个函数。然后你必须调用它-就像你对
pi()
所做的那样。顺便说一句,你有另外两个错误(我修正了,但不会解释),你真的不需要在这里上课。如果您仍在与参数、返回值和循环等基本概念作斗争,那么现在就不需要使用类。
def foo(arg1, arg2):
   print arg1, arg2

def bar():
   y = raw_input("y please")
   return y

what = "Hello"
whatelse = bar()
foo(what, whatelse)
import math

def Start():
    x = input("Please input what you want do to a number then the number; a whole number.\n(Example pi 2)\nYou can pow (pow 2 3; 2 to the power of 3),pi,square and cube: ").lower()
    x = x.split()
    Action = x[0]
    number = int(x[1])
    print ("Your number: " + str(number))
    return (Action, number)


class Cal:
    def pi(self, number):
        print ("Your number multiplied by Pi: " + str(math.pi * number))

def Again():
    y = input("Type 'Yes' to do another one if not type 'No': ").lower()

    if "yes" in y:
        print ("\n")
        args = Start()
        Work(*args)
        Again()
    elif "no" in y:
        pass

def Work(Action, *args):
    if Action.startswith("pi"):
        Cal().pi(*args)
    else:
        pass

def Main():
    args = Start()
    Work(*args)
    Again()

if __name__ == "__main__":
    Main()