你会如何使用在函数下面定义的变量?

时间:2013-12-19 12:54:28

标签: python class python-3.x

我正在尝试使用类来制作计算器,但我得到的错误是“变量未定义”

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

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))

class Cal:
    def pi():
        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")
        Start()
        Work()
        Again()
    elif "no" in y:
        pass

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

Start()
Work()
Again()

我收到“变量未定义” 我使用的是Windows 7和Python 3.3。可能的问题是什么?

2 个答案:

答案 0 :(得分:1)

您必须明确地将“变量”传递给需要它们的函数。您可以在任何编程教程中阅读有关此内容的更多信息(从Python的官方教程开始)。要从设置它们的函数中“获取”变量,您必须return变量。这真的是CS101 BTW

作为例子:

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

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

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

有关此内容的更多信息:http://docs.python.org/2/tutorial/controlflow.html#defining-functions

修复了你的脚本版本(nb在Python 2.7上进行了测试,其中包含input的hack,但应该在3.x上工作):

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()

答案 1 :(得分:0)

Start()功能中,输入

global Action

这样,变量将进入全局范围,因此可以从其他函数中看到它。

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

相关问题