在赋值之前引用变量'cmd_part_1'

时间:2013-03-09 01:27:08

标签: python python-2.7 python-3.x

我的机器人程序一直有这个错误:

  

在赋值之前引用的start.py:890局部变量'cmd_part_1'

代码:

try:
    my_alias = message.body.split(" ", 3)
    if len(my_alias) > 2:
        cmd_part_1 = my_alias[0]
        cmd_part_2 = my_alias[1]
    elif len(my_alias) < 2:
        cmd_part_1 = ""
        cmd_part_2 = ""
except Exception as e:
    cmd_part_1 = ""
    cmd_part_2 = ""

if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
    whole_body = message.body
    whole_body = whole_body.replace("call me ", "");
    whole_body = whole_body.replace(",", "&#44;");
    chat_message("<font color='#%s' face='%s' size='%s'>%s <b>%s</b></font>" % (font_color, font_face, font_size, random.choice(["Recorded! ^_^ I will now call you", "Registah'd, you are now", "Yo, dis mah big homie, I call dem", "Ye-a-a-ah, I guess I can call you that...", "If I have to.. I suppose I'll call you..", "I decided I will call you"]), whole_body), True)
    alias_flag = 0
    finished_proc = 1
    file = open("storage/flatfile/various/aliases.csv", "r")
    for line in file.readlines():
        alias_data = line.strip()
        alias_username, alias_nickname = alias_data.split(",", 1)

错误行:

if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您设置if的第一个elif块中有trycmd_part_1个语句。

如果这些if语句中的所有条件都不是True会发生什么?

在这种情况下,永远不会为cmd_part_1分配值。这是您的代码中发生的事情。解决这个问题,它会起作用。也许在那里添加else子句并为cmd_part_1cmd_part_2分配默认值。或者让其中一人拥有=

例如:

if len(my_alias) >= 2:

而不是:

if len(my_alias) > 2:

之后,正如eryksun在下面的评论中所建议的那样,您可以将elif替换为else