0

so getBoundedNumber() is to let the user input some numbers and return the input. My other functions base on the return value and do calculations. I tried to assign it to a global variable outside the function(like var=getBoundedNumber(...)),but instead of storing the value from function, it executes the function again and ask for user to input again. How do I fix this?Thank you!

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

This is my main function:

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

This is my menu function

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()
Not Allan
  • 5
  • 3
  • Note `exit` is not a statement but a function. If you want it to do anything, you have to call it: `exit()` – tobias_k Mar 31 '17 at 12:53

3 Answers3

0

Declare a global variable and then append the results before the return. Nevertheless you will not append the results because you are calling recursively the MAINMENU function so each execution will have it return value but it will be lost (unless you manage the calls and returns of MAINMENU)

Maybe you can do the same with a while-loop, and keep the values with a global variable.

Ximo
  • 1
  • 2
0

Another way of achieving the same:

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)
Len
  • 142
  • 8
0

Here's some modified code. Instead of using recursion in MAINMENU, we're now using a while loop. Now we can maintain state within the lexical scope of the method MAINMENU by using local variables chain_param and num_points, which store the values input by the user.

It's important to realize that each function has its own scope. Variables defined in one function are not going to be defined in another function. If we want to pass chain_param and num_points along to a new function, say do_magic, we have to send them as parameters to the method: i.e. do_magic(chain_param, num_points).

Likewise, we want do_magic to pass the calculated value back to MAINMENU, so we return that value and collect it in a new variable defined by the lexical scope of MAINMENU, called 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()

out

A - enter chain parameter a
N - enter number of points in chain
P - calculate and print chain results
Q - quit program
Enter your selection: A
Enter chain parameter between 0.5 and 4.5 2
Enter your selection: N
Enter chain parameter between 10 and 100000 100
Enter your selection: P
Magic Answer =  0.02
Enter your selection: Q
Crispin
  • 2,070
  • 1
  • 13
  • 16
  • Thanks for the help. But the thing is, I am in first year of university and just learn this language for 2 months. The code option[] is not taught by the professor and I have to do it within my knowledge. Is their another way to do it? – Not Allan Apr 01 '17 at 01:52
  • It is not working, it says must be real number, not Nonetype. I have changed my codes above, could you please read through it again? Sorry for the trouble :( – Not Allan Apr 01 '17 at 03:38
  • I can not keep helping if you keep changing the question, because it comes across like you are just asking me to do all the work for you. The code I have presented works. I suggest you take the time to understand how it works, and if you have any questions, please ask. And be specific. – Crispin Apr 01 '17 at 04:15
  • For the part that you do 'Magic answer', instead I use defined function like angle(numpoints, chain_param) to calculate stuff(the function is defined outside the MAIN). The problem I get is, even after I put stuff in selection A and N, for selection P, console gives me chain_para and num_points not defined – Not Allan Apr 01 '17 at 04:24
  • How do I understand this line: if chain_param and num_points: – Not Allan Apr 01 '17 at 07:17
  • we are checking that they are not equal to `None` or `0`, because otherwise we won't be able to evaluate the division. – Crispin Apr 01 '17 at 07:29