Receive not define error message even known declared global value - python

def buy():
while True:
items={"Armor": 25, "Sword": 25}
print("What do you want to buy?\n1/Armor +25 defense\t50 golds\n2/Sword +25 damage\t50 golds")
s1=input("Choose the item you want to buy (1 and/or 2 only): ")
try:
global a
a=int(s1)
if a in range (1,3):
break
except ValueError:
pass
buy()
print(a)
error message:
Traceback (most recent call last):
File "C:\code\work\The Role-Playing combat game.py", line 58, in <module>
print(a) NameError: global name 'a' is not defined
Line 58 is print(a)
I declared "a" as the global value, but somehow the interpreter gives me the error message. Please help, thanks.
Solved, declare "a" outside of the function first

Did you declare the a variable earlier in your code? Otherwise, calling global a before declaring it will throw that error. You need to put a = something before you call global a on it.

Related

Why am I getting a NameError when I've defined my variable name in a function?

I'm trying to build if/elif/else statements based on an input statement and a function I defined. When I run the code, the input statement and the function definition and call run fine, but then I get to my if/elif/else statements and I get a NameError, telling me that a variable I call up in the if/elif/else statements is not defined (even though I thought I defined it in the function).
For context, I'm new to Python, and I'm building code in Atom and running it in Command Prompt.
My input, function definition, and if statement code looks like this:
h, m, s, t = input('Rate each of the following Emotions and hit enter:\nHappiness (1-7):'), input('Meaningfulness (1-7):'), input('Stressfulness (1-7):'), input('Tiredness (1-7):')
h_int=int(h)
m_int=int(m)
s_int=int(s)
t_int=int(t)
def na():
add_h_m = h_int + m_int
div_h_m = add_h_m/2
add_s_t = s_int + t_int
div_s_t = add_s_t/2
net_affect = div_h_m - div_s_t
print(net_affect)
na()
if net_affect >= 3:
print("Doing Well")
elif net_affect <3 and net_affect >0:
print("Doing Okay")
else:
print("Not Good")
This is the Command Prompt output:
C:\Users\mrkev\Desktop\PAI 724>python ex2.py
Rate each of the following Emotions and hit enter:
Happiness (1-7):6
Meaningfulness (1-7):7
Stressfulness (1-7):4
Tiredness (1-7):3
3.0
Traceback (most recent call last):
File "C:\Users\mrkev\Desktop\PAI 724\ex2.py", line 16, in <module>
if net_affect >= 3:
NameError: name 'net_affect' is not defined
Where am I going wrong? I thought that by defining net_affect in the function, I could then use it as a variable in my program.
Thank you for your help!
Look for the 'variable scope' in your documentation or tutorials.
The net_affect variable is local to na function.
You cannot access it from the outside, and it is deleted when the function returns.
You can alternatively :
define the variable outside of the function, and indicate that you are using it in the function
net_affect = None
def na():
...
global net_affect
net_affect = div_h_m - div_s_t
return the value from the function and catch the returned value
def na():
...
net_affect = div_h_m - div_s_t
...
return net_affect # return the value
...
net_affect_new = na() # catch the value
Note: net_affect_new could be called net_affectbut they are not the same variables, they are in two different scopes.

"AttributeError" while accessing instance variables

Python is raising the below exception when running my script. Could somebody please explain why this is happening and how to fix it?
Traceback (most recent call last):
File "C:\Users\vinsunny\AppData\Local\Programs\Python\Python36\test.py", line 28, in <module>
test.my_func()
File "C:\Users\vinsunny\AppData\Local\Programs\Python\Python36\test.py", line 23, in my_func
print('non secret no. from test_func: ', self.number2)
AttributeError: 'Test' object has no attribute 'number2'"
class Test():
__class_secret_number = 100
def __secret_func(self):
self.number1 = 1
self.__secret_number1 = 11
print('You cannot see this unless accessing from the Class itself')
def test_func(self):
self.number2 = 2
self.__secret_number2 = 22
def my_func(self):
self.__secret_func()
print('Secret no. from class: ', self.__class_secret_number)
print('non secret no. from secret func: ', self.number1)
print('Secret no. from secret func: ', self.__secret_number1)
# These two prints raise an exception.
print('non secret no. from test_func: ', self.number2)
print('Secret no. from test_func: ', self.__secret_number2)
test = Test()
test.my_func()
At the time the offending print statement is executed, the number2 attribute on your Test instance has not been defined.
The first time the number2 attribute gets set is in the test_func() method. i.e. Attempting to access number2 before calling test_func() will result in the error you are observing.
You should assign a default value to self.number2 in the initializer for the Test class. You could also call test_func() before calling my_func(). But, either way, it's still good practice to initialize all instance attributes in Test.__init__.
The interpreter will raise an exception for the same reason when you try to access the undefined attribute __secret_number_2 in my_func().
test_func is never called, so number2 and __secret_number2 doesn't exist.
Need to call the function before try to access them, or init them with init method.

can't access global variable from inside a function in python

Below is my code
global PostgresDatabaseNameSchema
global RedShiftSchemaName
PostgresDatabaseNameSchema = None
RedShiftSchemaName = None
def check_assign_global_values():
if not PostgresDatabaseNameSchema:
PostgresDatabaseNameSchema = "Superman"
if not RedShiftSchemaName:
RedShiftSchemaName = "Ironman"
check_assign_global_values()
But i am getting an error saying
Traceback (most recent call last):
File "example.py", line 13, in <module>
check_assign_global_values()
File "example.py", line 8, in check_assign_global_values
if not PostgresDatabaseNameSchema:
UnboundLocalError: local variable 'PostgresDatabaseNameSchema' referenced before assignment
So can't we access or set the global variables from inside a function ?
global should always be defined inside a function, the reason for this is because it's telling the function that you wanted to use the global variable instead of local ones. You can do so like this:
PostgresDatabaseNameSchema = None
RedShiftSchemaName = None
def check_assign_global_values():
global PostgresDatabaseNameSchema, RedShiftSchemaName
if not PostgresDatabaseNameSchema:
PostgresDatabaseNameSchema = "Superman"
if not RedShiftSchemaName:
RedShiftSchemaName = "Ironman"
check_assign_global_values()
You should have some basic understanding of how to use global. There is many other SO questions out there you can search. Such as this question Using global variables in a function other than the one that created them.

variable defined in a function throws NameError: global name not defined when used in main

I'm trying to run my function: show_total() , but I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\file.py", in <module>
main()
File ".\file.py", in main
total_money = show_total(bags, coins, coin_to_bag)
NameError: global name 'coin_to_bag' is not defined
my code looks like:
def assign_coin_to_bag(bags, coins):
coin_to_bag = {}
print(bags)
print('\n')
print (coins)
print('\n')
for bag in bags:
print('For bag: ' + bag )
coin_type = input('\nWhich coin do you want to put in this bag? ') #e.g. 0.25 * 2
coin_amount = input('\nNumber of this type? ') #e.g. 0.25 * 2
mattress_status = 'stuffed'
for coin in coins:
coin_to_bag[bag] = [coin_type, coin_amount, mattress_status]
print(coin_to_bag)
return (coin_to_bag)
def main():
bags = gather_bag()
coins = gather_coin()
coins_in_the_bag = assign_coin_to_bag(bags, coins)
total_money = show_total(bags, coins, coin_to_bag)
main()
Thank you for your help!
coin_to_bag is a defined in the scope of assign_coin_to_bag, and is not accessible in main. You caught the return value of assign_coin_to_bag in coins_in_the_bag, and need to use that variable in your call to show_total.
There's a common error new programmers make, which is thinking the name of a variable needs to be the same wherever it's used, even across methods. In fact, the name of the variable means absolutely nothing to the computer. Good names are only there for humans.
As an exercise, we used to have students trace code like this:
def foo(one, three, two):
print "%s %s %s" % (one, two, three)
def bar():
return 1, 2, 4
three, two, one = bar()
foo(two, one, three)
Figure out what gets printed, and that will be good practice to break the variable naming habit.

python global error. It gives me at line 16 of my code. Where search is not defined why?

i have written down the code but it gives me an error. It gives the global error and says that it does not define the search. Please help me out guys.
def testSearch():
s = range(0,1000000)
raw_input('basic, -1')
print search(s,-1)
raw_input('binary, -1')
print search1(s,-1)
raw_input('basic, end')
print search(s,1000000)
raw_input('binary, end')
print search1(s,1000000)
s = range(0,10000000)
raw_input('basic, partway')
print search(s,1000000)
raw_input('basic, larger end')
print search(0,10000000)
>>> testSearch()
basic, -1
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
testSearch()
File "C:\Users\bangash\Documents\python files\lec8.py", line 17, in testSearch
print search(s,-1)
NameError: global name 'search' is not defined
So, where is your function search defined? You should define it as a function:
def search(a, b):
...
The function search has to be defined before the code in testSearch has been executed. The code in testSearch is executed when testSearch() is executed. So the following two will work
def search():
pass
def testSearch():
search()
testSearch()
or
def testSearch():
search()
def search():
pass
testSearch()
They both will work because, just before the testSearch() is executed, we got definition for search. But not this
def testSearch():
search()
testSearch()
def search():
pass

Categories

Resources