python code problem - python

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('/')

Related

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.

Logic and calling functions. Help me understand this code

I have some code that is basically a demo for how dict works. My problem is, I am not sure exactly when it is calling the process_order() function. It seems like the main loop (go_shopping) never calls it, but the script seems to work. The go_shopping function calls get_item, but that doesn't call process_order either. I am also having trouble with the line if not process_order(order, cart):. What does the if not part mean in this case? Is that where it is calling process_order? It doesn't seem like it from the print statements, other wise it should print 'if not' when you add an item to the cart dictionary object.
Am I on the right track or missing something simple?
Code:
#!/usr/bin/python3.5
def get_item():
print("[command] [item] (command is 'a' to add, 'd' to delete, 'q' to quit.)")
line = input()
command = line[:1]
item = line[2:]
return command, item
def add_to_cart(item, cart):
if not item in cart:
cart[item] = 0
cart[item] += 1
def delete_from_cart(item, cart):
if item in cart:
if cart[item] <= 0:
del cart[item]
else:
cart[item] -= 1
def process_order(order, cart):
command, item = order
if command == "a":
add_to_cart(item, cart)
print('added to cart')
elif command == "d" and item in cart:
delete_from_cart(item, cart)
elif command == "q":
return False
print ('end process_order func')
return True
def go_shopping():
cart = dict()
while True:
print ('start main loop')
order = get_item()
print ('exited process_order')
if not process_order(order, cart):
print ('if not')
break
print ('while loop end')
print (cart)
print ("Finished!")
go_shopping()
Thing is, I am not really sure of your problem. But you seem concerned with the moment when process_order method is called.
When you write
if not process_order(order, cart)
it must be seen as follows (just adding parentheses):
if (not process_order(order, cart))
So you're asking Python to do something if the condition not process_order(order, cart) is true. So, Python must know the boolean value of the expression not process_order(order, cart).
This expression is composed of a unary operator, not, and a non-elementary expression, process_order(order, cart). That latter expression needs to be evaluated, so Python has to run the process_order method.
Therefore, when you write if not process_order(order, cart), the process_order method is indeed executed.

Python input validation with class method check

OK, so I've been trying this for about 2 hours now and I can't seem to figure it out. I think I tried almost every possible algorithm combination and it still isn't working. Here it goes:
I'm trying to validate keyboard input in Python based on two condition (ordered by priority):
Check if input is integer
Check if input is vertex (class method for checking if the number given can be found as a key in a dictionary)
Here's the code:
def checkVertex(self, x):
ok = 0
for key in self.__inv:
if key == x:
ok += 1
break
for key in self.__outv:
if key == x:
ok += 1
break
if ok == 2:
return True
return False
def checkInt(number):
if number.isdigit() is False:
return False
return True
def readVertex(msg, graf): <-- this is the issue
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
vertex = raw_input(msg)
while checkInt(vertex) is False:
print invalid_input
vertex = raw_input(msg)
if checkInt(vertex) is True:
vertex = int(vertex)
if graf.checkVertex(vertex) is True: <-- this bloody line is not working right
return vertex
else:
continue
return int(vertex)
source = readVertex("Give source vertex (by number): ", G)
dest = readVertex("Give destination vertex (by number): ", G)
cost = int(raw_input("Give cost: "))
print G.addEdge(source, dest, cost)
The problem that I'm getting is that the first condition works, so if I input a letter it will print an error, but if I input a number and that number isn't in the keys of the dictionary it will still return it.
So graf.checkVertex(vertex) always returns True in the above code even though I know for a fact that it works because I've tried the function with the same input in the shell and it returned False.
Let me give you an example, let's say I have this dict:
{0: [], 1: [], 2: [], 3: [], 4: []}
Screen recording of example:
Your validation only runs while checkInt(vertex) is False: - if it is a valid integer the first time, you never check the rest. It's not that graf.checkVertex(vertex) doesn't work; it's never called. Instead, try:
def readVertex(msg, graf, invalid_input):
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
while True:
vertex = raw_input(msg)
if checkInt(vertex) and graf.checkVertex(int(vertex)):
return int(vertex)
print invalid_input
or
def readVertex(msg, graf, invalid_input):
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
while True:
try:
vertex = int(raw_input(msg))
except ValueError:
print invalid_input
else:
if graf.checkVertex(vertex):
return vertex
print invalid_input

Django Views Incrementing Variables

When I increment one of my variables, it only goes up to 2 instead of 3. The default value is 1. I am not sure what I am missing. Any help is appreciated.
def unanswered(request, template ='unanswered.html'):
phone_number = Pool.objects.order_by('?')[0]
pool = Pool.objects.order_by('?')[0]
pool_list = Pool.objects.all()
number_attempts = Pool.objects.filter(phone_number=phone_number).count()
# unanswer number action
if pool_list:
if number_attempts > 3:
return number_attempts
else:
x = number_attempts
x += 1
print x 'returns 2'
store = Pool(id=phone_number.id,
phone_number = phone_number.phone_number,
un_answered=x, answered=0)
store.save()
payload = {'pool':pool,}
return render_to_response(template, payload, context_instance=RequestContext(request))
There is no any for loop or while loop in your code, so if initial number_attempts is 1, it will incremented to 2 and complete the flow.
I see you want to store attempts in the DB, but the way you are doing is not correct. You are passing id=phone_number.id to Store(...), which will try to update existing record if exists with given id. So Pool.objects.filter(phone_number=phone_number).count() always returns 1.
You may want to change it to
store = Pool(phone_number = phone_number.phone_number,
un_answered=x, answered=0)
So for the next request, Pool.objects.filter(phone_number=phone_number).count() will give you 2.
Update after the comment:
All I want is to update the un_answered field from 1,2,3.
In that case, don't use .count() to get number of failed attempts use the field from object that has that counter.
So instead of
number_attempts = Pool.objects.filter(phone_number=phone_number).count()
you can do this
try:
store = Pool.objects.get(phone_number=phone_number)
number_attempts = store.un_answered
# FIX : the original code used a bare except clause.
# Bare except clauses are EVIL. DONT use bare except clauses. NEVER.
# Or thou shall burn in the flames of hell for your eternal death....
except Pool.DoesNotExist:
store = Pool(phone_number = phone_number.phone_number,
un_answered=1, answered=0)
store.save()
number_attempts = 1
...
if pool_list:
if number_attempts > 3:
return number_attempts
else:
x = number_attempts
x += 1
print x 'returns 2'
store.un_answered = x
store.save()

NameError: global name 'this_submit' is not defined

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.

Categories