The variables are defined before the if statement.
if (len(Item.objects.filter(owner=request.session['id'])) > 0):
for x in Item.objects.filter(owner=request.session['id']):
if (x.item == forageitem):
x.amount = x.amount + 1
x.save()
messages.success(request, "You found a " + forageitem +".")
return redirect("/dashboard")
else:
continue
The function passes through the if statement just fine, but if the item in question is not found, it will not create a new object in the Item class, instead it will give me an error.
For some reason, I am getting a ValueError (didn't get an HttpResponse. Instead it reutunred None.) at this part of my code:
else:
Item.objects.create(item=forageitem, owner=User.objects.get(id = request.session['id']), description=item[forageitem], amount=1)
messages.success(request, "You found a " + forageitem +".")
return redirect("/dashboard")
I am almost certain I didn't change anything here, it was working before.
Ideas, anyone? Please help.
EDIT: The problem turned out to be int the logic.
I erased the else: statement and made it into a code that runs if it passes through the if: statement without finding anything.
Related
I'm trying to get my code to get a string of data from a sensor, and then do something when it reads a specific value.
The following code is how I'm receiving the data now (this is just a test) the function is called earlier in the code at the time where I want it to be called.
def gettemperature(self)
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
This code works, and returns the temperature value rounded to the terminal, but how could I, instead of printing the value to the terminal, make it so when that string of rounded value is say, 200 degrees, then it prints the temperature value? instead of printing it every 2 seconds (the frequency of the data being received, as per another part of the code)
Using something like
if temp = 200
then print(blahblah)
in short, the above code is what I'm trying to do. If the temp equals a certain value, then something else will happen.
That last code doesn't work. I'm pretty new to coding, so I'm assuming I'm either not going about this the right way, or the syntax of how I'm going about trying to get that value to do something isn't correct (obviously)
Thanks for any help! I'm surprised I got this far, haha.
It would be better if your function gettemperature would return something and then print the result in the condition:
def gettemperature()
temp = board.temp_sensor
return temp
temp = gettemperature()
if temp == 200:
print("Temperature is " + str(round(temp)) + " degrees.")
Before using stackoverflow, I'd recommend learning all this stuff from some basic course, as you'll get to learn the stuff yourself rather then get the answer from someone else.
Try learning conditional statements.
what you want is, to put a conditional statement which triggers if temperature is greater than 200.
If the temp is always a number in string data type, you can use the below code.
def gettemperature(self):
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
temp=int(temp) #typecasting string datatype to integer
if temp == 200:
print("Temperature is high")
def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.
Why is this creating an infinite loop? And if it isn't creating one, why does the program freeze up? Not like IDLE stops responding, It just stops like I created a infinite loop and the only thing it does is input(). Try the code out to see what I mean.
(also, tell me if the for's are correct in the comments please)
Accounts = {}
def create_account(x,y,z,a):
global Accounts
Checked = False
while Checked == False:
if x in Accounts:
print("Sorry, that name has already been taken")
print("Please choose a new name")
x = input()
for dictionary in Accounts:
for key in dictionary:
if a in key:
print("Sorry, password is invalid or not avalible")
print("Please choose a new password")
a = input()
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
print(Accounts[x])
Your code creates an infinite loop because there is nothing to stop it.
while checked == False will do exactly what it sounds like, it will loop over the code over and over until checked = True OR until you break
break will simply stop the loop, allowing the program to finish.
checked = True will also stop the loop
I think that what you are trying to do is something like this:
This code is untested
Accounts = {}
def create_account(x,y,z,a):
global Accounts
Checked = False
while Checked == False:
if x in Accounts:
print("Sorry, that name has already been taken")
print("Please choose a new name")
x = input()
else:
passwordOk = True
for dictionary in Accounts:
for key in dictionary:
if a in key:
passwordOk = False
break
if not passwordOk:
break
if not passwordOk:
print("Sorry, password is invalid or not avalible")
print("Please choose a new password")
a = input()
else:
Checked = True # this is the important part that you missed
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
print(Accounts[x])
Just for you to know, your code can be optimized. I tried to solve your issue by modifying as minimum code as possible, so that you could understand the problem
There are two issues causing this.
As you say,
the print() is before the input(), and the print never outputs, so it doesn't get that far
However, let's take a step back: the print statements are inside the block if x in Accounts:. At the very first line, you set Accounts to be an empty dictionary (Accounts = {}), so no matter what x is, at that point, x in Accounts will never be true - there's nothing in it.
Now, you do have a line that adds items to Accounts:
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
However, as other people have pointed out, you'll never get here - it's outside the loop, and the loop never exits because Checked is never set to True, nor is a break called.
Your program then is essentially just going through the same few steps that don't do anything:
Does Checked == False? Yep, continue the loop.
Is x in Accounts? Nope, skip this block.
For every dictionary in Accounts, do some stuff, but Accounts is empty, so I don't need to do anything.
Does Check == False? Yep, continue the loop.
In my function, I type in a raw_input after my return statement and then I proceed to call my function. When I call my function the raw_input is totally ignored and only the return statement works.
def game():
#This selects 5 community cards from the pick_community function
community = pick_community(5)
card_4 = community[3]
card_5 = community[4]
first_3 = community[0:3]
return first_3
river = raw_input("If you are done with the round hit enter:" )
try:
if river =="":
return card_4
except:
print "Dont cheat man"
exit()
That:
return first_3
returns and therefore ends the function.
The remaining code is just ignored, because you will never get past the return.
Because a return statement gets out of the function, so the rest of the code wont execute
If you want to return first 3 values and then continue in code you can do it using yield. It basically inserts values into generator, then in the end return the whole generator.
https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/
more here, or google for even more :)
I am getting the following Error Message :
Traceback (most recent call last):
File "/Volumes/KINGSTON/Programming/Assignment.py", line 17, in <module>
Assignment()
File "/Volumes/KINGSTON/Programming/Assignment.py", line 3, in Assignment
My code is:
def Assignment():
prompt = 'What is your PIN?'
result = PIN
error = 'Incorrect, please try again'
retries = 2
while result == PIN:
ok = raw_input(Prompt)
if ok == 1234:
result = menu
else:
print error
retries = retries - 1
if retries < 0:
print 'You have used your maximum number of attempts. Goodbye.'
Assignment():
would really appreciate a little help if anyone knows where i am going wrong and can explain
That particular error is raised because when you say result = PIN, PIN doesn't actually exist. Since it isn't in quotes, Python assumes it is a variable name, but when it goes to check what that variable is equal to, it doesn't find anything and raises the NameError. When you fix that, it will also happen with prompt since you later refer to it as Prompt.
I'm not sure if this is your full code or not, so I'm not sure what the other issues could be, but it looks like you are using result and PIN to control your while loop. Remember that a while loop runs until the condition it is checking is False (or if you manually break out of it), so instead of declaring the extra variables, you could start with something like this:
def Assignment():
# No need to declare the other variables as they are only used once
tries = 2
# Go until tries == 0
while tries > 0:
ok = raw_input('What is your PIN?')
# Remember that the output of `raw_input` is a string, so either make your
# comparison value a string or your raw_input an int (here, 1234 is a string)
if ok == '1234':
# Here is another spot where you may hit an error if menu doesn't exist
result = menu
# Assuming that you can exit now, you use break
break
else:
print 'Incorrect, please try again'
# Little shortcut - you can rewrite tries = tries - 1 like this
tries -= 1
# I'll leave this for you to sort out, but do you want to show them both
# the 'Please try again' and the 'Maximum attempts' messages?
if tries == 0:
print 'You have used your maximum number of attempts. Goodbye.'