如何在 Python 函数之间传递数据

74 阅读2分钟

有一位程序员在用Python编写一个程序时遇到了问题,程序中 Menu 选项 1 和 Menu 选项 2 之间无法传递数据。在 Menu 选项 1 中正确存储的数据,在返回到 Menu 选项 2 时,好像它从未进入过选项 1 一样。

2、解决方案 要解决这个问题,我们需要了解函数的范围。在 Python 中,变量的作用范围仅限于其所在的函数或模块。这意味着,如果在一个函数中定义一个变量,在另一个函数中就无法访问它。

为了在函数之间传递数据,我们可以使用 return 语句。return 语句可以将数据从一个函数返回到另一个函数。

huake_00063_.jpg 下面是修改后的代码:

def menu(a): #2nd thing to happen 
    menuend = 'a'
    while menuend not in 'e':
    http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
        menuend = raw_input("Type anything other then 'e' to continue:\n")
        print "What would you like to do ?"
        menudo = 0
        print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
        menudo = input("Enter Selection:")
        if (menudo == 1):
            menuchck = 0
            menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
            if menuchck in ["Yes","yes","y","Y"]:
                a = m1()
            else:
                print "I'm sorry,",nam,",for the confusion, lets try again\n"
                menu()
        elif (menudo == 2):
            menuchck1 = 0
            menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
            if menuchck1 in ["Yes","yes","y","Y"]:
                m2(a)
            else:
                print "I'm sorry,",nam,",for the confusion, lets try again\n"
                menu()
        elif (menudo == 3):
            print "Entered 3"
        elif (menudo == 4):
        print "Entered 4"
        else:
            print "Anything Else Entered"

def course(): #3rd thing to happen 
    b = {}
    while True:
        while True:
            print "\n",name,", please enter your courses below ('e' to end):"
            coursename = raw_input("Course Name:")
            if (coursename == 'e'):
                break
            will = None
            while will not in ('y','n'):
                will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
            if will=='y':
                b[coursename] = {}
        print "\n",name,", current course load:\n",b
        coursechck = None
        while coursechck not in ('y','n'):
            coursechck = raw_input("Are your courses correct (y/n)")
        if coursechck =='y':
            return b
        else:
            b = {}
            print

##Menu Options##
def m1():
    a = course()
    return a

def m2(a):
    print "Excellent",name,"lets see what courses your enrolled in\n"
    print a

###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)

raw_input("This is the end, my only friend the end")

在修改后的代码中,我们在 m1() 函数中使用 return 语句将数据返回到 menu() 函数中。在 m2() 函数中,我们使用 a 参数来接收从 menu() 函数中传递过来的数据。这样,我们就能够在 Menu 选项 1 和 Menu 选项 2 之间传递数据了。