繁体   English   中英

Python 中的“赋值前引用的局部变量”

[英]“Local variable referenced before assignment” in 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()

这只是另一个indention问题。 您在menu()分配之前调用truth_table() 您可以将def truth_table():行缩进,直到您的except行增加一个制表符或 4 个空格。

你的代码应该是这样的,你对 go 很好:

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()

您需要移动truth_table function 的定义:

  1. 关于使用它的if/else块,或
  2. 完全退出menu (将其删除,并放在menu功能之前或之后)

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

尝试这个。 您提到的错误不再出现。 (可能还有其他设计错误,但这至少解决了您提到的问题)。

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() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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