简体   繁体   English

变量未定义错误,即使它是?

[英]Variable not defined error, even though it is?

I'm making a discord.py bot, and I'm trying to implement a command that will tell you how much time there is until the period ends.我正在制作一个 discord.py 机器人,并且我正在尝试实施一个命令,该命令将告诉您在此期间结束前还有多长时间。 The code works by itself, but if I try to implement it into the bot I get this error:该代码本身可以工作,但是如果我尝试将其实现到机器人中,则会出现此错误:

NameError: name 'timee' is not defined NameError:未定义名称“timee”

(The variable is called 'timee' since I also use the time.sleep() function later) (该变量称为“timee”,因为我稍后也使用 time.sleep() 函数)

This is the code it has a problem with:这是它有问题的代码:

def setTime():
    global timee

    print(timee)

    if timee > 59 and timee < 100:
        timee -= 100
        timee += 60
    elif timee > 159 and timee < 200:
        timee -= 100
        timee += 60
    elif timee > 259 and timee < 300:
        timee -= 100
        timee += 60

I have the print(timee) there to test if it thinks it's defined or not, which it doesn't.我有print(timee)来测试它是否认为它已定义,而它没有。

This is my code that calls the setTime function (and should also set timee)这是我调用setTime函数的代码(也应该设置 timee)

if currentTime < start:
    timee = start - currentTime

    print(timee)

    setTime()
    doThing()

    await client.send_message(message.channel, content = "School hasn't started yet! It starts in %s:%s" % (hours, minutes))
    print("%s got the time left." % message.author)

Edit: The 'timee' variable is declared outside of the if statement and the function as well.编辑:'timee' 变量也在 if 语句和函数之外声明。

Edit 2: I tried what someone commented, (The comment is deleted now) which is doing def setTime(timee): instead of编辑 2:我尝试了某人评论的内容(该评论现在已删除)正在执行def setTime(timee):而不是

def setTime():
    global timee

And that works.这有效。 I don't know if this is inefficient or what, but it works.我不知道这是效率低下还是什么,但它有效。 ALSO, this exact same code works if It's not in the discord bot.另外,如果它不在 discord bot 中,这个完全相同的代码也可以工作。

Doing def setTime(timee): (as opposed to having def setTime(): and just trying to use the global variable) and then calling 'timee' from inside the function like that seems to fix everything.def setTime(timee): (而不是def setTime():并且只是尝试使用全局变量) 然后从函数内部调用 'timee' 似乎可以解决所有问题。

If there is some more efficient or better way to do this then do tell, but for now I'll probably stick with this, since it's what I've found to work.如果有一些更有效或更好的方法来做到这一点,那么请告诉我,但现在我可能会坚持这一点,因为我发现这是可行的。

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

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