local variable 'highest' referenced before assignment - python

I've tried calling out through the function but still pops up this error message.
def mostExpensiveStock(self):
mostexpStock = 0
for r in self.getstockList():
if r.value(r.getamountPur, r.getpricePur) > mostexpStock:
mostexpStock = r.value(r.getamountPur, r.getpricePur)
highest = str(r) + "with a total value of RM" + str('%.2f'%mostexpStock)
return highest

Suppose that either:
self.getstockList() is empty; or
r.value(...) is negative for all members of self.getstocklist()
Then, your code will never assign any value to highest and thus your attempt to return highest will cause the exception you are seeing.
Suppose that you'd like to return None in this case. Then begin by providing a default value for highest
def mostExpensiveStock(self):
highest = None
mostexpStock = 0
...

I believe the problem is sometimes the if block isn't going to trigger. With the way your code is written if that were the happen you would still try to return the value highest, however without the if block triggering the value won't be created.
You could look going to an if else block.

Related

Value of string to be a trigger

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")

Class method changing variable

I am kind of new to python and I am facing a lot of trouble because for some reason this value within my class method is updating by it self even though I didn't touch it. I can't even make it constant... Here is the relevant piece of code that does it.
the method that is called:
def swapping(self,pos,puzzle):
print('Old puzzle \n',puzzle)
# Getting Zero point index
zero = obj.null_pos(puzzle)
# Getting Index of varied position
var = puzzle[pos[0]][pos[1]]
#Swappping values
puzzle[zero[0,0],zero[0,1]] = var
puzzle[pos[0], pos[1]] = 0
new_puzzle = puzzle
print('New_puzzle \n',new_puzzle)
return new_puzzle
# The code has been snipped into relevant parts only
for i in range(len(child_node)):
# Check the hn of each node
print(child_node[i])
#where it occurs:
num_mispl = obj.misplaced_tiles(nod.swapping(child_node[i],new_puz))
# <-- new_puz #value changes and i didn't assign it to anything
temp_stor.append(num_mispl)

Checking that array doesn't contain negative numbers, and running function again if it does

My task today is to create a way for checking if a function's output contains negative numbers, and if it does, then I must run the function until it contains no negative numbers.
I'll post the full code later in the post, but this is my attempt at a solution:
def evecs(matrixTranspose):
evectors = numpy.linalg.eig(matrixTranspose)[1][:,0]
return evectors
if any(x<0 for x in evectors) == False:
print(evectors)
evecs() is my function, and evectors is the output array, but I only want to print evectors if there are no negative entries in it. I also want to later add that if there are negative entries in it, the code should run the evecs function again until it finds an evectors that has no negative entries.
However, whenever I run it I get the error:
global name evectors is not defined
Here's a link to my code, and the full output from the iPython console. http://pastebin.com/3Bk9h1gq
Thanks!
You have not declared the variable evectors other than within the scope of your function evecs.
evectors = evecs(matrixTranspose)
if any(x<0 for x in evectors) == False:
print(evectors)
EDIT
There are several issues:
Indentation is VERY important in Python. MarkovChain and evecs are two seperate functions. You had your evacs function indented an extra level in, embeddeding it within MarkovChain.
MarkovChain should return matrixTransponse if you plan to use it in another function call.
As a result of the above issue, your function call to MarkovChain needs to be assigned to a variable, matrixTranponse, otherwise you will get an error stating that matrixTranspose is not defined when you make your function call to evecs with it.
Since the initialization of the variable matrixTranspose isn't set until the function call to MarkovChain is completed, the remainder of your logic will need to be re-ordered.
I have applied all the above changes below and added comments to the changed areas:
def MarkovChain(n,s) :
"""
"""
matrix = []
for l in range(n) :
lineLst = []
sum = 0
crtPrec = precision
for i in range(n-1) :
val = random.randrange(crtPrec)
sum += val
lineLst.append(float(val)/precision)
crtPrec -= val
lineLst.append(float(precision - sum)/precision)
matrix2 = matrix.append(lineLst)
print("The intial probability matrix.")
print(tabulate(matrix))
matrix_n = numpy.linalg.matrix_power(matrix, s)
print("The final probability matrix.")
print(tabulate(matrix_n))
matrixTranspose = zip(*matrix_n)
return matrixTransponse # issue 2
# issue 1
def evecs(matrixTranspose):
evectors = numpy.linalg.eig(matrixTranspose)[1][:,0]
return evectors
matrixTranponse = MarkovChain(4, 10000000000) # issue 3
# issue 4
evectors = evecs(matrixTranspose)
if any(x<0 for x in evectors) == False:
print(evectors)

List index out of range - python array error

File "C:\Users\Tom\Desktop\Tetris!\tetris.py", line 206, in typeSet
Globals.blockArray[i].x.append(7)
IndexError: list index out of range
I get the above error for the 4th line in typeSet
At initialization:
def main():
initialize()
def initialize():
Globals.running = True
addBlock()
class Globals:
running = True
blockArray = []
blockNum = 0
And then later on:
def addBlock():
Globals.blockArray.append(block())
class block:
def __init__(self):
self.id = Globals.blockNum
Globals.blockNum += 1
self.x = []
self.y = []
self.landed = False
self.blockType = 1#random.randint(1,6)
self.typeSet()
def typeSet(self):
i = self.id
if self.blockType == 1:
#square(i)
Globals.blockArray[i].x.append(7)
Globals.blockArray[i].y.append(0)
Globals.blockArray[i].x.append(7)
Globals.blockArray[i].y.append(1)
Globals.blockArray[i].x.append(8)
Globals.blockArray[i].y.append(0)
Globals.blockArray[i].x.append(8)
Globals.blockArray[i].y.append(1)
Edit: added more code and switched it so the id should start at 0. Error code hasn't changed
Not enough code. The error tells you the exact problem. Globals.blockArray does not have a member at position i. That's why you shouldn't work with global variables when you can avoid them, since it can be a hard time making sure your global variables have the expected values in them.
I'm not sure but maybe you want to do
Globals.blockArray.append(self)
in the init function, and also increase Globals.blockNum after the assignment to self.id.
Every time an instance of block is created, Globals.blockNum is incremented by 1 and self.id is set to the current value of Globals.blockNum.
Later (in typeSet) self.id is used to index into Globals.blockArray.
The error occurs when Globals.blockArray doesn't have at least self.id + 1 items in it.
If Globals.blockNum keeps increasing and its value is used (indirectly) to index into Globals.blockArray, this will likely cause the error (unless something causes Globals.blockArray to keep growing too.
While nothing immediate comes to mind looking at your code above, the first thing I would try would be to print the contents of Globals.blockArray, and Globals.blockArray[i].

python, how to write an iterative function

I am quering a database for some paramaters which depend on a attribute called count! count can be incremented incase the 1st query does not return anything. Here is a sample code
sls = {(213.243, 55.556): {}, (217.193, 55.793): {}, (213.403, 55.369): {}}
for key in sls.keys:
if not sls[key]:
ra, dec = key[0], key[1]
search_from_sourcelist(sl, ra,dec)
count = 1
def search_from_sourcelist(sl, ra,dec):
dist = count/3600.0
sls[(ra,dec)] = sl.sources.area_search(Area=(ra,dec,dist))
return
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This is to be done for all keys in sls dictionary, untill all the keys have a value!!
Here is the most fundamental recursive function
def countdown(n):
if n == 0:
return "Blastoff"
else:
print "T minus %s" % n
return countdown(n-1)
You will notice that countdown returns itself with a modified argument, in this case n but -1, so if you actually followed this all the way through you would get
(-> indicates a call)
countdown(5) -> countdown(4) -> countdown(3) -> countdown(2) -> countdown(1) -> countdown(0) #stop
So now you understand what a recursive function looks like you realize you never actually return a call of your own function, thus your code is not recursive
We use recursion because we want to boil a task down to its simplest form then work from there, so a good example of this would be the mcnuggets problem. So you need to tell us what you are trying to achieve and how it can be made a smaller problem (or more importantly why.) Are you sure you cannot do this iteratively? remember you don't want to blow your stack depth because python is NOT tail recursive by standard
Recursion is useful when you find a way to reduce the initial problem to a "smaller version of itself".
The standard example is the factorial function
def fac(n):
return n * fac(n-1) if n > 1 else 1
Here you reduce the problem of calculating the factorial of n to calculating the factorial of n-1.
In your code there is no such "reduction". You just increment a value and start the same problem over again. Thus, I recommend you solve it iteratively.
I'm not sure that you need a recursive algorithm for this.
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This can be done with a while loop as follows:
for key, value in sls.iteritems():
if not value:
ra, dec = key[0], key[1]
count = 1
while not search_from_sourcelist(sls, ra, dec):
count += 1
But if you really do want to do this recursively, you can do it as follows, leave a comment and I'll write it up.
Further, you should look into your search_from_sourcelist function, as it always returns None

Categories