Python Nameerror: Name Is Not Defined

Python NameError: name is not defined

Define the class before you use it:

class Something:
def out(self):
print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

NameError: Name 'trys1' is not defined

First of all, some code feedback: You should almost never use global variables for anything. It is extremely rare that you'll actually need them, and they cause all sorts of namespace problems if you aren't careful - this being an example.

The actual issue: You haven't actually created a global variable called trys1 outside of the suche function. Global variables need to be defined on the global namespace, and then calling them inside the function simply tells Python that you're trying to modify that global variable, rather than a new local one.

If that's confusing, hopefully the example below will clarify. The below code will return 2, because you told the foo function that you're trying to modify the c that you defined above, not a local c that you created within the confines of the function.

c = 1
def foo():
global c
c = c+1
return c

print(foo())

This time, the below code should give the same NameError that you received (although I haven't tested), because you're trying to tell the foo function to modify the global variable c, but there is no global variable c.

def foo():
global c
c = c+1
return c

print(foo())

Now, the below code will simply modify the c variable inside the function.

def foo():
c = 1
c = c+1
return c

print(foo())

Python NameError: name 'print_x' is not defined

This is because you wrote your function AFTER you called it. Python is a scripting language, so you need to have the function declared before you call it.



Related Topics



Leave a reply



Submit