-2

我正在编写一个代码来模拟 python 中的公告板系统(BBS)。

使用此代码,我想让用户选择查看已输入的消息或输入稍后查看的消息。

我的代码如下:

def BBS():
 print("Welcome to UCT BBS")
 print("MENU")
 print("(E)nter a message")
 print("(V)iew message")
 print("(L)ist files")
 print("(D)isplay file")
 print("e(X)it")

selection=input("Enter your selection:\n")

 if selection=="E" or selection=="e":
    message=input("Enter the message:\n")
 elif selection=="V" or selection=="v":
    if message==0:
        print("no message yet")
    else:
        print(message)
 elif selection=="L" or selection=="l":
    print("List of files: 42.txt, 1015.txt")
 elif selection=="D" or selection=="d":
    filename=input("Enter the filename:\n")
    if filename=="42.txt":
        print("The meaning of life is blah blah blah ...")
    elif filename=="1015.txt":
        print("Computer Science class notes ... simplified")
        print("Do all work")
        print("Pass course")
        print("Be happy")
    else:
        print("File not found")
 else:
    print("Goodbye!")

BBS()

输入消息时,代码应该在选择 v 后显示消息,或者如果没有输入消息,如果选择 v,则应该显示“还没有消息”。

我得到错误:

Traceback (most recent call last):
  File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in BBS
builtins.UnboundLocalError: local variable 'message' referenced before assignment

在使用 WingIDE 时选择 v 时。

请帮助我更正此代码。

4

2 回答 2

1

该变量message一个 if分支中分配。如果选择了另一个分支,则永远不会定义该变量。

首先给它一个空值:

 message = None

 if selection=="E" or selection=="e":
      message=input("Enter the message:\n")
 elif selection=="V" or selection=="v":
      if not message:
          print("no message yet")
      else:
          print(message)
于 2013-03-29T16:56:37.340 回答
0

你遇到的问题是message你的函数中的一个局部变量。当函数结束时,它给出的值会丢失,即使你再次运行该函数。为了解决这个问题,您需要更改代码中的某些内容,但更改的内容可能取决于您希望如何组织程序。

一种选择是将其设为全局变量,如果函数运行多次,则可以重复访问该变量。为此,首先在全局级别(函数外部)为其分配一个值,然后使用global函数内部的语句使 Python 清楚它是您要访问的全局名称。

message = None

def BBS():
    global message
    # other stuff

    if foo():
        message = input("Enter a message: ")
    else:
        if message:
            print("The current message is:", message)
        else:
            print("There is no message.")

Another option would be to stick with a local variable, but keep the logic of your program all within the same function. That is, if you want a user to be able to make several entries, you need to have a loop inside the function to contain them. Here's how that might look:

def BBS():
   message = None # local variable

   while True: # loop until break
       if foo():
           message = input("Enter a message: ")
        elif bar():
            if message:
                print("The current message is:", message)
            else:
                print("There is no message.")
        else:
            print("Goodbye!")
            break

A final, and more complicated (but also more permanent and scalable) option would be to use something outside of your program to store the message. This lets it persist between runs of the program, and perhaps be seen by different users at different times. For a serious system I'd suggest a database, but for a "toy" system you can probably get away with simple text files. Here's an example of that:

def BBS():
    if foo():
        with open("message.txt", "w") as f:
            message = input("Enter a message: ")
            f.write(message)
    else:
        try:
            with open("message.txt", "r") as f:
                message = f.read()
                print("The current message is:", message)
        except (FileNotFoundError, OSError):
            print("There is no message.")
于 2013-03-29T17:20:51.993 回答