如何存储函数返回的值而不再执行该函数?

时间:2017-03-31 07:04:06

标签: python python-3.x ipython

所以getBoundedNumber()是让用户输入一些数字并返回输入。我的其他函数基于返回值并进行计算。我试图将它分配给函数外部的全局变量(如var = getBoundedNumber(...)),但不是存储函数中的值,而是再次执行函数并要求用户再次输入。我该如何解决这个问题?谢谢!

def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
            print(ee)
        except ValueError:
            print(' not a valid input')
    exit

return AA

这是我的主要功能:

def MAIN():

while True:

    xx=menu()

    if xx == 'A':
        aa=getBoundedNumber(0.5,4.5,1)

    elif xx == 'N':
        numpoints=getBoundedNumber(10,100000,1)

    elif xx == 'P':


        print('  Parameter a:%20.3f'%aa,'[m]')#console gives me aa not defined
        print('  Number of points:%20d'%numpoints)#console gives me numpoints not defined
        print('  Length:%20.3f'%chainlength(xs,ys),'[m]')#this function requires value from aa and numpoints so it won't execute.
        print('  Angle with support:%20.3f'%anglewithsupport(g_,dd,aa,numpoints))
        print('  Net force:%20.3f'%netforce(),'[N]')

    elif xx == 'Q':
        break
    else:
        print(' not a valid option')

exit

这是我的菜单功能

def menu():
print('Main menu choices')
print('   A - enter chain parameter a' )
print('   N - enter number of points in chain' )
print('   P - calculate and print chain results')
print('   Q - quit program') 
while True:      
    try:
        SELECTION = input('Enter your selection: ')

        if SELECTION.upper()== 'A':

            break
        elif SELECTION.upper() == 'N':
            break
        elif SELECTION.upper()=='P':
            break
        elif SELECTION.upper()=='Q':
            break

        else:
            print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
    exit
return SELECTION.upper()

3 个答案:

答案 0 :(得分:0)

声明一个全局变量,然后在返回之前附加结果。然而,你不会附加结果,因为你正在递归调用MAINMENU函数,所以每次执行都会返回它但它会丢失(除非你管理MAINMENU的调用和返回)

也许您可以使用while循环执行相同操作,并使用全局变量保留值。

答案 1 :(得分:0)

达到同样目的的另一种方法:

def getBoundedNumber(qq,ww,ee,aList):

    while True:
        try:
            x = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(x)==float or int,'not a valid input'
            if qq<= x <= ww:
                aList.append(x)
                break
            else:
                print(ee)
        except ValueError:
            print(' not a valid input')
            exit
    return aList

def MAINMENU():
    print('A - enter chain parameter a' )
    print('N - enter number of points in chain' )
    print('P - calculate and print chain results')
    print('Q - quit program')
    AA = []
    try:
        SELECTION = input('Enter your selection: ')

        if SELECTION.upper() == 'A':
            AA = getBoundedNumber(0.5,4.5,1,AA)
            MAINMENU()    
        elif SELECTION.upper() == 'N':
            AA=getBoundedNumber(10,100000,1,AA)
            MAINMENU()
        elif SELECTION.upper() == 'P':
         #calculations that base on user input from A and N    
        elif SELECTION.upper() == 'Q':
            exit
        else:
            print('%r is not a valid option'%SELECTION)
            MAINMENU()
    except ValueError:
        print('%r is not a valid option'%SELECTION)

答案 2 :(得分:0)

这是一些修改后的代码。我们现在使用的是MAINMENU循环,而不是在while中使用递归。现在,我们可以使用局部变量MAINMENUchain_param来维护方法num_points的词法范围内的状态,该变量存储用户输入的值。

重要的是要意识到每个功能都有自己的范围。在一个函数中定义的变量不会在另一个函数中定义。如果我们想将chain_paramnum_points传递给新功能,比如说do_magic,我们必须将它们作为参数发送到方法:即do_magic(chain_param, num_points)

同样,我们希望do_magic将计算出的值传递回MAINMENU,因此我们return该值并将其收集到由{{1}的词法范围定义的新变量中},名为MAINMENU

magic_answer

def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
                print(ee)
        except ValueError:
            print(' not a valid input')

    return AA

def do_magic(x,y):
    if x and y:
        return x / y

def MAINMENU():
    print('A - enter chain parameter a' )
    print('N - enter number of points in chain' )
    print('P - calculate and print chain results')
    print('Q - quit program')

    chain_param = None
    num_points = None
    magic_answer = None
    try:
        while True:
            SELECTION = input('Enter your selection: ')

            if SELECTION.upper() == 'A':
                chain_param = getBoundedNumber(0.5,4.5,1)

            elif SELECTION.upper() == 'N':
                num_points = getBoundedNumber(10,100000,1)

            elif SELECTION.upper() == 'P':
                #do something with chain_param and num_points to get magic_answer
                if chain_param and num_points:
                    magic_answer = do_magic(chain_param,num_points)
                print('Magic Answer = ', magic_answer)

            elif SELECTION.upper() == 'Q':
                return 1
            else:
                print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
        return -1

MAINMENU()