如何将文字分配给变量,然后在模块中使用相同的变量?

时间:2013-03-29 16:54:16

标签: python python-3.x

我正在编写一个代码来模拟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。

请帮我更正此代码。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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.")

另一个选择是坚持使用局部变量,但保持程序的逻辑都在同一个函数中。也就是说,如果您希望用户能够创建多个条目,则需要在函数内部包含一个循环来包含它们。这可能是这样的:

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

最终,更复杂(但也更永久和可扩展)的选项是使用程序之外的东西来存储消息。这使它可以在程序的运行之间保持,并且可能在不同的时间被不同的用户看到。对于一个严肃的系统,我建议使用一个数据库,但对于一个“玩具”系统,你可以使用简单的文本文件。这是一个例子:

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.")