NameError: global name 'this_submit' is not defined - python

The following function seems really simple, but I keep getting:
NameError: global name 'this_submit' is not defined.
Ideas?
def sort_nodes():
host_list=Popen(hosts_cmd.split(),stdout=PIPE).communicate()[0].strip()
exec_list=Popen(exec_cmd.split(),stdout=PIPE).communicate()[0].strip()
if submit_cmd == '':
submit_list = [x for x in host_list if x not in exec_list]
else:
submit_list=Popen(submit_cmd.split(),stdout=PIPE).communicate()[0].strip()
for host in host_list:
if host in exec_list:
this_exec == 'Exec'
else:
this_exec == ''
if host in submit_list:
this_submit == 'Submit'
else:
this_submit == ''
output="%s,%s,%s\n" % (host,this_submit,this_exec)
ofile.write(output)

the correct syntax is:
this_submit = 'Submit'
and
this_submit = ''
In python the single = is the assignment operator.
== checks if the value of two operands are equal or not, if yes then condition becomes true.

you wrote == instead of =. fix it and everything will be fine.

Related

Python: How to determine if a String can be converted to an integer with no issues

I am writing a program that has multiple functions to execute, and the user selects which one runs by inputting a number. I also want the user to be able to let the user cancel the request by typing "cancel".
Right now this is my code:
func = input("Requested Operation: ")
if func == 'Cancel' or func == 'cancel':
break
elif func == '' or func == ' ' or func == '0':
func = 0
elif type(int(func)) is int:
func = int(func)
else:
fail = True
Context: Function 0 displays a list of the available items to choose from, so I want whitespace or 0 to work as displaying the project list. If the user types "Cancel" or "cancel" it will end the program.
The problem I am having is line 6 (the 2nd elif). My goal is to set the fail variable to True if the user inputs a string that isn't a cancel command, so the code breaks right there and starts over. The problem is, how do I preemptively check if a string can be converted to an integer in the first place? My current iteration returns the error invalid literal for int() with base 10: 'asdg' (asdg being the random nonsense that should make fail = True).
Also, I understand this method is probably super inefficient. Essentially, I want the conditional to be "if func is cancel, break. If func is whitespace or '0', then it equals 0. If func is some non-0 integer, convert the string to an integer and continue. Otherwise, set fail to True and break."
My knowledge of python is minimal so I would very much appreciate a full explanation or link to documentation so I can learn as much as possible.
Thanks in advance :)
Edit: This is the entire module
import projects.dice_app as dice_app
import projects.text_to_math as text_to_math
def main():
f = open("readme_files/index.txt")
p = open("readme_files/projects.txt")
print(f.read())
func = 0
while True:
fail = False
func = input("Requested Operation: ")
if func == 'Cancel' or func == 'cancel':
break
elif func == '' or func == ' ' or func == '0':
func = 0
elif type(int(func)) is int:
func = int(func)
else:
fail = True
break
if func == 0:
p = open("readme_files/projects.txt")
print(p.read())
elif func == 1:
dice_app.dice_func()
elif func == 2:
text_to_math.ttm_func()
else:
print("Invalid operation. Please try again.")
if __name__ == "__main__":
fail = False
main()
while fail == True:
main()
elif func.isnumeric():
func = int(func)
try :
func = int(func)
except ValueError:
print('not a number')
This should work

UnboundLocalError: local variable 'text' referenced before assignment

UnboundLocalError: local variable 'text' referenced before assignment
Hi, I'm getting this error 'UnboundLocalError: local variable 'text' referenced before assignment'. How do you fix this?
Here is my Code:
even = None
def is_even(num):
if num % 2 == 0:
even = True
return even
elif num % 2 != 0:
even = False
return even
def lastmes():
if even == True:
text = "The last value of even is True"
elif even == False:
text = "The last value of even is False"
return text
print(lastmes())
print(is_even(51))
Here is my error message:
Traceback (most recent call last):
File "main.py", line 17, in <module>
print(lastmes())
File "main.py", line 15, in lastmes
return text
UnboundLocalError: local variable 'text' referenced before assignment
You should do 3 things.
First, make even variable inside the is_even function global. You are just creating another local variable and setting it's value which wont change the even you created outside the function.
def is_even(num):
global even #Here
if num % 2 == 0:
even = True
return even
elif num % 2 != 0: #You should change this to just an else but this works too
even = False
return even
Second, change the elif in your lastmes function to else. If you plan on using elif and want to consider a possibility for even to be None, then you should add another else to deal with the None possibility.
def lastmes():
if even == True:
text = "The last value of even is True"
else:
text = "The last value of even is False"
return text
Third, call is_even before lastmes so that the values are calculated, before checking them and displaying the messages.
print(is_even(50))
print(lastmes())
If even is neither True nor False, then text is never defined. even is set to None at the beginning of your program.

Any better way to find entry in table in a table?

Here's my code, can I do it better/faster?
phoneFound = False
for host in nm.all_hosts():
if 'mac' in nm[host]['addresses']:
if nm[host]['addresses']['mac'] == phone_mac:
phoneFound = True
if phoneFound == False:
print 'sh'
You could break out of the loop as soon as you found one. Alternatively (and better) you could do this in one line using the built-in function any, like so:
phone_found = any(nm[host]['address'].get('mac', None) == phone_mac for host in nm.all_hosts())

Syntax error at second definition in Python

def specificChecker(someThing, checker):
if checker == None:
return someThing
elif checker == True:
return not someThing
else:
return None
def whatDoesTheCheckerSay(someThing):
if specificChecker(someThing) == someThing:
return 'The checker value was False on that one.'
elif specificChecker(someThing) == not someThing:
return 'The checker value was True on that one.'
elif specificChecker(someThing) == None:
return 'Something irregular happend. The checker value wasn\'t None or True.'
else:
return 'Something went really wrong. This doesn\'t even not work.'
reallySomeThing = input('Type in really some thing: ')
theChecker = input('Set the checker to something: ')
print(specificChecker(reallySomeThing, theChecker))
print(whatDoesTheCheckerSay(reallySomeThing)) # This can be made more efficient, right?
def one(someShit):
return someShit + ' AWWW YEAH!'
def two(someShit):
return one(someShit)
print(two(input('Type in some kind of stuff: ')))
I'm a self-taught beginner, so surely it's something awkwardly basic. I'm using the IDLE shell and have repeatedly gotten a syntax error at the second definition statement of my codes. Please help?
You cannot use the line:
elif specificChecker(someThing) == not someThing:
This must be written
elif specificChecker(someThing) != someThing:
to be valid Python.
This is also valid but is perhaps less readable:
elif (specificChecker(someThing)) == (not someThing):
After OP edit:
The new error is the mismatch in arguments (always 1) to a function that requires 2 arguments. You have to pass two arguments to specificChecker not one
Line 12: elif specificChecker(someThing) == not someThing:
If you want to check if some variable is not some variable, used is not for boolean or != for values and strings

python code problem

i have this code:
class Check(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
self.redirect('/')
to check whether the user is registered or not.
but it gives me an error:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/Users/zainab_alhaidary/Desktop/الحمد لله/check.py", line 23, in get
if s is 0:
UnboundLocalError: local variable 's' referenced before assignment
what should i do???
Define s before to assign it a value (also, change the test on s):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
s=0 # <- init s here
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s == 0: # <- change test on s
self.redirect('/')
Why exactly are you loading all users, then looping through them, just to find one? Use a where clause:
be = "SELECT * FROM Benutzer WHERE benutzer=:1"
c = db.GqlQuery(be, user)
user_from_db = c.get()
if user_from_db is not None: # found someone
dostuff()
else:
self.redirect('/')
You're using 's' before you assign something to it. Add an 's = 0' in the appropriate location.
You want to set s to 0 before the for loop starts. If the query returns zero items, your for loop doesn't loop even once, so s is undefined.
Also, you should use if s == 0: instead of if s is 0:. In CPython, they are both equivalent, but you shouldn't rely on the fact. See: the documentation for PyInt_FromLong and "is" operator behaves unexpectedly with integers.
Your problem is that if c is an empty list then the code in the for loop is never run and s never gets set, hence the error:
UnboundLocalError: local variable 's' referenced before assignment
What the error is telling you that you're referencing - i.e. using - s before it has any value - i.e. before a value has been assigned to it.
To fix this you just ensure s always is assigned a value:
s = 0
for x in c:
if x.benutzer == user:
s = 1
break
else:
s = 2
In the case that c is empty the if statement in the loop never gets executed
you should set s=0 before the for loop
I don't know why you are doing this, but if I understand your code correctly, you have s=1 when x.benutzer == user, and s=2 otherwise (shouldn't this be s=0 if you are going to check against 0?).
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
self.redirect('/')
Anyway, here's my solution:
if not any(x.benutzer == user for x in c):
self.redirect('/')

Categories