Python中的“分配前引用的局部变量”

时间:2019-09-19 02:45:52

标签: python

我想做的是通过打印真值表来测试一些逻辑语句。当我选择菜单的选项2时,除1个问题外,其他所有功能都正常运行:

  

分配前引用的本地变量'truth_table'

该如何解决?

我不确定是否可以将真值表放在第二选择中而不是调用它。

import itertools
import sys

def menu() :
    print ("Testing logical equivalences")
    print ("1. View instructions")
    print ("2. Create a truth table")
    print ("3. Exit")
    choice = input ("Please select an option: ")
    if choice =="1":
            print("=================================================================================")
            print ("sdasd")
            print()
            print("Examples will be shown below")
            print("Any of the five inputs have to be lower case and only")
            print("Example: A and B (NOT C) would look like ' a and b and(not c)'")
            print("All inputs are converted to lower-case. Do NOT use '' marks!")
            print()
            print("LIMITS OF THE APP ===============================================================")
            print("1. App won't allow any inputs beside (a,b,c,d,e)")
            print("2. To ensure correct use of parentheses (inner statements are evaluated first)")
            print("3. The limit of inputs is 5")
            print("4. Evaluation of the logical statement will be print in the next availabe column")
            print("5. If your statement can't be evaluate, check for syntax and brackets")
            print()
            print()
            wait = input("Press ENTER to return to the menu. ")
            menu()
    elif choice =="2":
        truth_table()
    elif choice =="3":
        print("Program Terminated")
        sys.exit()
    else:
        print ("Invalid input")
        menu()

    def truth_table():
        while True:
            try:
                inps = int(input("Please enter the number of inputs you want 1 - 5. "))
                if inps <1 or inps>5:
                    print ("1 input minimum, 5 max")
                else:
                    break
            except:
                ValueError
                print ("You must input a number between 1 and 5")

    truths = list(itertools.product([False,True], repeat=inps))

    statement = input("Please input the logical statement e.g. (a and b) not c.")
    statement = statement.lower()

    print ("A AND B OR C")##changeme A is item[0], B item[1] ...E item[4] etc.
    print ("A\t\tB\t\tC\t\tD\t\tE\t\tF")
    print("-"*20*inps)

    for item in truths:
        pos = 0
        if inps == 1:
            a = item[0]
        elif inps == 2:
            a,b = item[0], item[1]
        elif inps == 3:
            a,b,c = item[0], item[1], item[2]
        elif inps == 4:
            a,b,c,d = item[0], item[1], item[2], item[3]
        else:
            a,b,c,d,e = item[0], item[1], item[2], item[3], item[4]
            pos = 0
        while pos < inps:
            print (item[pos],end = "\t\t")
            pos += 1
        try:
            truth = eval(statement) ###turns user input into code
            print (truth)
        except:
            print ("Unable to evaluate. Check statement")
        print()
        wait = input("Press ENTER to return to the menu. ")
        menu()
menu()

3 个答案:

答案 0 :(得分:1)

这只是另一个indention问题。您在分配之前,正在truth_table()中调用menu()。您可以将def truth_table():行的行缩至except行的一个标签或4个空格。

您的代码应如下所示,您可以使用:

import itertools
import sys

def menu() :
    print ("Testing logical equivalences")
    print ("1. View instructions")
    print ("2. Create a truth table")
    print ("3. Exit")
    choice = input ("Please select an option: ")
    if choice =="1":
            print("=================================================================================")
            print ("sdasd")
            print()
            print("Examples will be shown below")
            print("Any of the five inputs have to be lower case and only")
            print("Example: A and B (NOT C) would look like ' a and b and(not c)'")
            print("All inputs are converted to lower-case. Do NOT use '' marks!")
            print()
            print("LIMITS OF THE APP ===============================================================")
            print("1. App won't allow any inputs beside (a,b,c,d,e)")
            print("2. To ensure correct use of parentheses (inner statements are evaluated first)")
            print("3. The limit of inputs is 5")
            print("4. Evaluation of the logical statement will be print in the next availabe column")
            print("5. If your statement can't be evaluate, check for syntax and brackets")
            print()
            print()
            wait = input("Press ENTER to return to the menu. ")
            menu()
    elif choice =="2":
        truth_table()
    elif choice =="3":
        print("Program Terminated")
        sys.exit()
    else:
        print ("Invalid input")
        menu()

def truth_table():
    while True:
        try:
            inps = int(input("Please enter the number of inputs you want 1 - 5. "))
            if inps <1 or inps>5:
                print ("1 input minimum, 5 max")
            else:
                break
        except:
            ValueError
            print ("You must input a number between 1 and 5")

    truths = list(itertools.product([False,True], repeat=inps))

    statement = input("Please input the logical statement e.g. (a and b) not c.")
    statement = statement.lower()

    print ("A AND B OR C")##changeme A is item[0], B item[1] ...E item[4] etc.
    print ("A\t\tB\t\tC\t\tD\t\tE\t\tF")
    print("-"*20*inps)

    for item in truths:
        pos = 0
        if inps == 1:
            a = item[0]
        elif inps == 2:
            a,b = item[0], item[1]
        elif inps == 3:
            a,b,c = item[0], item[1], item[2]
        elif inps == 4:
            a,b,c,d = item[0], item[1], item[2], item[3]
        else:
            a,b,c,d,e = item[0], item[1], item[2], item[3], item[4]
            pos = 0
        while pos < inps:
            print (item[pos],end = "\t\t")
            pos += 1
        try:
            truth = eval(statement) ###turns user input into code
            print (truth)
        except:
            print ("Unable to evaluate. Check statement")
        print()
        wait = input("Press ENTER to return to the menu. ")
        menu()
menu()

答案 1 :(得分:0)

您需要移动truth_table函数的定义:

  1. 关于使用它的if/else块,或
  2. 完全不在menu中(请确认并放在menu函数之前或之后)

按原样,它是menu的局部变量,仅当您到达def truth_table行时才分配,但是您试图在此之前调用它。

答案 2 :(得分:0)

尝试一下。您提到的错误不再出现。 (可能存在其他设计错误,但这至少可以解决您提到的问题。)

import itertools
import sys

def menu() :

    def truth_table():
        inps = None
        while True:
            try:
                inps = int(input("Please enter the number of inputs you want 1 - 5. "))
                if inps <1 or inps>5:
                    print ("1 input minimum, 5 max")
                else:
                    break
            except:
                ValueError
                print ("You must input a number between 1 and 5")
        return inps

    print ("Testing logical equivalences")
    print ("1. View instructions")
    print ("2. Create a truth table")
    print ("3. Exit")
    choice = input ("Please select an option: ")
    if choice =="1":
            print("=================================================================================")
            print ("sdasd")
            print()
            print("Examples will be shown below")
            print("Any of the five inputs have to be lower case and only")
            print("Example: A and B (NOT C) would look like ' a and b and(not c)'")
            print("All inputs are converted to lower-case. Do NOT use '' marks!")
            print()
            print("LIMITS OF THE APP ===============================================================")
            print("1. App won't allow any inputs beside (a,b,c,d,e)")
            print("2. To ensure correct use of parentheses (inner statements are evaluated first)")
            print("3. The limit of inputs is 5")
            print("4. Evaluation of the logical statement will be print in the next availabe column")
            print("5. If your statement can't be evaluate, check for syntax and brackets")
            print()
            print()
            wait = input("Press ENTER to return to the menu. ")
            menu()
    elif choice =="2":
        inps = truth_table()
    elif choice =="3":
        print("Program Terminated")
        sys.exit()
    else:
        print ("Invalid input")
        menu()

    if inps is not None:
        truths = list(itertools.product([False,True], repeat=inps))

        statement = input("Please input the logical statement e.g. (a and b) not c.")
        statement = statement.lower()

        print ("A AND B OR C")##changeme A is item[0], B item[1] ...E item[4] etc.
        print ("A\t\tB\t\tC\t\tD\t\tE\t\tF")
        print("-"*20*inps)

        for item in truths:
            pos = 0
            if inps == 1:
                a = item[0]
            elif inps == 2:
                a,b = item[0], item[1]
            elif inps == 3:
                a,b,c = item[0], item[1], item[2]
            elif inps == 4:
                a,b,c,d = item[0], item[1], item[2], item[3]
            else:
                a,b,c,d,e = item[0], item[1], item[2], item[3], item[4]
                pos = 0
            while pos < inps:
                print (item[pos],end = "\t\t")
                pos += 1
            try:
                truth = eval(statement) ###turns user input into code
                print (truth)
            except:
                print ("Unable to evaluate. Check statement")
            print()
            wait = input("Press ENTER to return to the menu. ")
            menu()
menu()