在函数外部定义变量时遇到问题(Python)

时间:2011-08-15 17:31:49

标签: python function

我是python的新手,我正在尝试创建一个简单的程序,你有文本菜单,我必须使用函数来完成大部分工作(习惯于在程序中使用函数)。所以我试图在这个程序中使用一个函数从用户那里获取第一个,第二个,也可能是第三个数字。我需要能够重用这个函数,这样我才能从用户那里获得所述数字,但是我遇到的问题是只能在函数中使用这些变量而在其他任何地方都没有。任何建议都会有帮助!这是代码:

option = 1
while option !=0:
    print "\n\n\n************MENU************"
    print "1. Counting by one"
    print "2. Fibbonacci Sequence"
    print "0. GET ME OUTTA HERE!"
    print "*" * 28

    option = input("Please make a selection: ") #counting submenu
    if option == 1:
        print "\n\n**Counting Submenu**"
        print "1. Count up by one"
        print "2. Count down by one"
        print "3. Count up by different number"
        print "4. Count down by different number"

        countingSubmenu = input("Please make a selection: ")
        def getNum():
            firstNum = input("Please state what number to start at: ")
            secondNum = input("Please state what number to end at: ")
            if countingSubmenu == 3 or countingSubmenu == 4:
                thirdNum = input("Please state what increment you would want to go up by: ")

         if option == 1:
             getNum()
             for x in range(firstNum, secondNum+1):
                print x
             print "End of test."

2 个答案:

答案 0 :(得分:5)

变量是定义它们的函数的本地变量。您可以尝试让函数返回这些值:

def getNum():
    firstNum = input("...")
    secondNum = input("...")
    thirdNum = input("...")
    return firstNum, secondNum, thirdNum

if option == 1:
    firstNum, secondNum, thirdNum = getNum()

答案 1 :(得分:1)

或者,您可以使用全局变量。例如:

global a_var
  def a_function():
   global a_var   
   a_var = 3

a_function()
print a_var

但是,使用返回可能更清晰。