Home python Python 3: Error 'name' ... 'is not defined "

Python 3: Error ‘name’ … ‘is not defined “




I want to make a “avtostatus” for the bot using. To do this, str (status_message_from_cycle) exposing its value in the cycle:

def status_cycle1 ():
  status_message_from_cycle = str ( "test 1")
def status_cycle2 ():
  status_message_from_cycle = str ( "test 2")
interval = 2
def statusPeriodicFunction ():
  status_cycle1 ()
  status_cycle2 ()
def startTimer ():
  threading.Timer (interval, startTimer) .start ()
  statusPeriodicFunction ()

Later, this value is set in the config file:

self.status_message = str (status_message_from_cycle)

But after the code interpretation goes:

File “/media/mint/F3D8-BADB/MusicBot/musicbot/config.py”, line 88, in init
self.status_message = str (status_message_from_cycle)
NameError: name ‘status_message_from_cycle’ is not defined

Answer 1, Authority 100%

In Python variable scope local by default. For example, the following code will not change the global variable

var_a = "original value"
def modify_var_a ():
 var_a = "changed value" # created a new variable
modify_var_a ()
print (var_a) # & gt; & gt; & gt; original value

To force the use of a variable from an outer scope is necessary to use the keyword global with the name of a variable before it will be used in the domestic scope. If there are several nested scopes, you can gain access to either the global scope by using global , or else to the “nearest” using nonlocal .

var_a = 1
def modify_a ():
 var_a = 2 # another variable with the same name as the global
 def modify_a1 ():
  global var_a
  var_a = 3
 modify_a1 ()
 def modify_a2 ():
  nonlocal var_a
  var_a = 5
 modify_a2 ()
 print ( "modify_a :: var_a =", var_a)
modify_a ()
print ( ":: var_a =", var_a)

modify_a :: var_a = 5
:: var_a = 3

The same is happening in your case. The functions of the status_cycle1 creates a new variable status_message_from_cycle but it is not beyond the function scope. You must first create a global, then specify the functions that use it is global, and then modify it.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions