简体   繁体   中英

Variable not being assigned value when returned from subprogram? Python 3?

I am trying to return a value from my subprogram, but when trying to use the variable in the main program, it comes up with an error saying it has not been assigned a value.

correct = 0
def subprogram():
    correct2 = 0
    loop = 0
    while loop == 0:
        loop2 = 0
        memberID = input("Please enter your member ID: ")
        if memberID == "1495":
            print("Login successful!")
            loop = 1
            correct2 = 1
        else:
            print("Login unsuccessful.")
            while loop2 == 0:
                decision = input("<T>ry Again or <E>xit to Menu? ")
                if decision == "t" or decision == "T":
                    print("Ok, restarting.")
                    print("")
                    loop2 = 1
                elif decision == "e" or decision == "E":
                    print("Ok, exiting to main menu.")
                    print("")
                    loop2 = 1
                    loop = 1
                    correct2 = 0
                else:
                    print("-----------------------------------------------------")
                    print("Sorry, this is not a valid answer. Please try again.")
                    print("-----------------------------------------------------")
        continue
    return correct2

#main
while correct == 0:
    print ("Are you a member?")
    member = input("<Y>es or <N>o? ")
    if member == "y":
        correct = subprogram()
        if correct2 == 0:
            correct = 0
        elif correct2 == 1:
            correct = 1
    elif member == "Y":
        correct = subprogram()
        if correct2 == 0:
            correct = 0
        elif correct2 == 1:
            correct = 1
    elif member == "n" or member == "N":
        print("Ok, not a problem! Welcome!")
        correct = 1
    else:
        print("-----------------------------------------------------")
        print("Sorry, this is not a valid answer. Please try again.")
        print("-----------------------------------------------------")
        correctVIP = 0
print("END")

How would I fix this error? Thankyou.

In your main while loop you don't define the correct2 variable so it throws an error when you try to do:

if correct2 == 0:

You assign the result of subprogram to correct :

correct = subprogram()

where you probably mean to do:

correct2 = subprogram()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM