Getting an attribute error when the value is already assigned - python

After you get to the part when the program prints 6 it gives me the error that is mentioned below. Even though the value if properly attributed. I want it to print a 6 when the Mario.x_location value is equal to the LifeShroom.x value. Then after that, I want it to increase the value of the Mario.x_location by one whenever w is pressed. Type yes than press enter, and type w to see what I mean. What am I doing wrong?
start = input('say yes: ')
class Mario:
x_location = 4 #location of you
class LifeShroom:
x = 4 #location of the object.
if start == 'yes':
while start == 'yes':
command = input('') #press enter here, after you input yes.
if command == 'w':
Mario.x_location += 1 #change Mario.x_location
print(Mario.x_location,)
rules = [Mario.x_location == LifeShroom.x,]
if all(rules):
LifeShroom = True
if LifeShroom:
print(6) #type w again after it prints 6 and you will get the error below.
Exact error that I got:
Traceback (most recent call last):
File "main.py", line 25, in <module>
rules_8 = [Mario.x_location == LifeShroom.x,
AttributeError: 'bool' object has no attribute 'x'

I can say that you are doing a infinite loop. There is no scape for the while loop.
In the first if-statement isn't runned the first if (if command == 'w':), but runs the other two. In the first one, it destroies your class (LifeShroom = True). But it is True, so it will run the third. Your variable LifeShroom is not more a class but a boolean (True).
Next loop there is no more LifeShroom class, so no LifeShroom.x class atribute.

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.

If-Else statement not asking for input in Python

I am trying to write a basic Twitter scraper in Python and while I have it so that it can scrape for hard coded terms, I'm trying to set it to take the search term from user input.
While my if/else statement accepts input when asked, it then fails to run stating that rawinput is not defined. The rawinput is within the if statement I've included my code below
I should mention I'm fairly new to Python.
I've tried removing the rawinput from the if/else and kept it separate but the same issue happens.
userinp = input("Select search type. 1 = tweets. 2 = people")
if userinp == 1:
entry = rawinput
query = u'q='
elif userinp == 2:
entry = rawinput
query = u'f=users&vertical=default&q='
searchurl = baseurl + query + entry
The expected result is that the user selects option 1 or 2 then is asked to enter their search term.
Results are:
Select search type. 1 = tweets. 2 = people1
Traceback (most recent call last):
File "Scrape.py", line 22, in <module>
userentry = rawinput('enter search term')
NameError: name 'rawinput' is not defined
Thanks in advance for any help given.
Use input() instead and don't forget the parentheses!
Additionally, input() converts your input to a string, so your if condition will never be met if it uses integers. Consider replacing with if userinp == '1': and elif userinp == '2':.
It should be raw_input() not rawinput. so your code should be like this...
userinp = input("Select search type. 1 = tweets. 2 = people")
if userinp == 1:
entry = raw_input()
query = u'q='
elif userinp == 2:
entry = raw_input()
query = u'f=users&vertical=default&q='
searchurl = baseurl + query + entry

python pass function with argument to another function

I'm trying to create a function that gets two functions as argument and I get an error .
What I have done is created a function named "parent" that takes 2 functions as argument (ux and ui). But ux has arguments too, and it gets them from the parent function:
import ID_Ui as Ui
ui = Ui.admin_panel()
# ui returns something like this :
'''Please choose one of the options below :
Please press 0 if you want to exit the program .
Please press 1 if you want to exit to main menu .
Please press 2 if you want exit to previous section .
Please press 3 if you want to create/modify user account .
Please press 4 if you want to create/modify company account .
Please press 5 if you want to create/modify document type .
Please press 6 if you want to create/modify document ID . '''
def child(*ui):
user_choice = ui
if user_choice == 3:
return 3
elif user_choice == 4:
return 4
elif user_choice == 5:
return 5
else:
return 'error'
def parent(ux, ui):
user_choice = ui
x = user_choice
if user_choice == 0:
return 0
elif user_choice == 1:
return 1
elif user_choice == 2:
return 2
else:
ux(x)
print(parent(child(), ui))
I expect that when I input a number other than [0:2] , it runs the ux function and passes it the x variable as its argument. But I get the following error regarding ux(x) line:
TypeError: 'int' object is not callable
First of all, I'll assume that the function menu_conditions you are invoking is in fact the parent function, but I believe you should fix that.
Second, when you run child() on the last line, it returns a number, or the string error. If you wanted to be able to run child inside the parent folder, simply pass it without parentheses, like that:
print(parent(child, ui))

Why do I get the error "'function' object is not subscriptable'

This is my code block
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
elif len(get_close_matches(words, definitions.keys())) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus[get_close_matches(words, definitions.keys())]
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
I expected to receive the meaning of the word "Grief". However, I kept receiving the error : function object is not subscriptable.
Here is the terminal log, just in case it might help:
My-MacBook-Pro:Python Adwok$ python3 dictionary.py
Look Up: GRERFAG
Did you mean grief instead? Enter 'Y' if yes or 'N' if no: Y
Traceback (most recent call last):
File "dictionary.py", line 22, in <module>
print(thesaurus(words))
File "dictionary.py", line 13, in thesaurus
return thesaurus[get_close_matches(words, definitions.keys())]
TypeError: 'function' object is not subscriptable
Please point out even the smallest details, I would appreciate that very much.
As stated by the error stack, in line 13 you are accessing thesaurus as if it was a list/dictionary (or any subscriptable object). Since thesaurus is a function (which is not subscriptable), you get an error. Thus, you need to invoke the function (instead of accessing it):
thesaurus(get_close_matches(words, definitions.keys()))
Also, you should notice:
At the end of your code you are correctly invoking the thesaurus function by calling print(thesaurus(words))
Consider reusing the result of get_close_matches to avoid multiple calls to the same function (which can lead to performance degradation if the call is resource consuming).
I suggest you the following solution:
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))

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