Python 3: Is this a float or a list? - python

I have a class which has the attribute 'latest_level' and this should be a floating point number. I then have a method which includes latest_level in an equation to return another floating point number. In this method, if I use the line:
def relative_water_level(self):
level = float(self.latest_level)
I get the output:
TypeError: float() argument must be a string or a number, not 'list'
Which I assume means self.latest_level is a list. If I change this line to:
def relative_water_level(self):
level = float(self.latest_level[0])
I get the output:
TypeError: 'float' object is not subscriptable
Which I assume means self.latest_level is a float. Anybody have any idea why this is happening and how I can get it to treat self.latest_level as a float?
Edit: I don't try and subscript later. The rest of the method is:
level = float(self.latest_level[0])
low = float(self.typical_range[0])
high = float(self.typical_range[1])
return ((level - low)/high)
And the Error specifies that the Error is in the line mentioned above
File "C:\Users\rache\Documents\Flood Warning\partia-flood-warning
system\floodsystem\station.py", line 58, in relative_water_level
level = float(self.latest_level[0])
TypeError: 'float' object is not subscriptable

subscriptable object refers to something which implements __getitem__() method. you might be changing latest_level's type. I have added a sample code which will produce the same error.
class Level:
latest_level = 20.0
def getLevels(self):
self.latest_level = [20,30]
def relative_water_level(self):
level = float(self.latest_level[0])
print(level)
waterLevel = Level()
waterLevel.relative_water_level()
waterLevel.getLevels()
waterLevel.relative_water_level()
for debugging use type(self.latest_level) before float(self.latest_level) and change according to stack trace.

Problem solved. Turns out some of the flood monitoring stations I'm importing data from are producing messed up data with lists of numbers all over the place, so I've just had to ignore those stations for now. Thanks for all your help and good luck to any of you who live near those rivers!

Related

appending to list within list gives AttributeError: 'int' object has no attribute 'append'

when executing the following code, I get the error message "AttributeError: 'int' object has no attribute 'append'". I know this error occurs when I try to append to an integer, for example, which is not the case here since I checked that via type(section[len(section)-1]) which returned list
def increasing_section(a_list):
section = [[a_list[0]]]
i = 1
while i < len(a_list):
if a_list[i-1] < a_list[i]:
section[len(section)-1].append(a_list[i])
else:
section.append(a_list[i])
i += 1
return section
The error comes from this line:
section[len(section)-1].append(a_list[i])
because at some point, when your if condition will not be met, the following line:
section.append(a_list[i])
will add an integer in section and the first line will produce error as section[len(section)-1] will be an integer
I'm not sure what exactly you are trying to do, but to fix this you need to change section[len(section)-1].append(a_list[i]). Because section[len(section)-1] will return an integer and integer doesn't have append method, so if you want to insert an element to a list at a particular index, try section.insert(index, value)

int() argument must be a string or a number, not 'generator'

I am stuck with two errors, and I assume it comes from my misuse of the classes, but I can't figure out how to fix that...
I get :
AttributeError: Organism instance has no attribute 'remove'
or
int() argument must be a string or a number, not 'generator'
def filtre_vecteurs(organisms):
nb_organisms = len(organisms)
vector_size = len(organisms[0].vector)
for i in range(vector_size):
tmp = 0
for j in range(nb_organisms):
organisms[j].vector[i] = int(organisms[j].vector[i])
tmp += organisms[j].vector[i]
if tmp == nb_organisms :
for j in range(0, nb_organisms):
organisms[j].remove(organisms[j].vector[i])
return organisms
"organisms" is a list of objets
"organisms[0].vector" :vector of the first object of the list
a vector looks like this [1,0,1,1...]
thanks a lot for your help !
Your errors are:
AttributeError: Organism instance has no attribute 'remove'
This is in line organisms[j].remove(organisms[j].vector[i])
Here, it seems organisms[j] which is an organism has no remove() method. You probably want to remove the element organisms[j].vector[i] from organisms[j].vector:
organisms[j].vector.remove(organisms[j].vector[i])
int() argument must be a string or a number, not 'generator'
This is due to line:
organisms[j].vector[i] = int(organisms[j].vector[i])
Are you sure that organisms[j].vector[i] is a number/string?. Can you try printing it and see if it is indeed a number/string?
Here are things to look at:
Error 1:
What is the type of organisms[j].vector[i]? From the error message, it appears as though it is a generator, so has no conversion to int.
Error 2:
What does your organism class look like?
From the line:
organisms[j].remove(organisms[j].vector[i])
which I presume causes your second error. Your Organism class has no method called 'remove'.

What is a 'NoneType' object?

I'm getting this error when I run my python script:
TypeError: cannot concatenate 'str' and 'NoneType' objects
I'm pretty sure the 'str' means string, but I dont know what a 'NoneType' object is. My script craps out on the second line, I know the first one works because the commands from that line are in my asa as I would expect. At first I thought it may be because I'm using variables and user input inside send_command.
Everything in 'CAPS' are variables, everything in 'lower case' is input from 'parser.add_option' options.
I'm using pexpect, and optparse
send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)
send_command(child, SNMPSRVUSRCMD + snmpuser + group + V3AUTHCMD + snmphmac + snmpauth + PRIVCMD + snmpencrypt + snmppriv)
NoneType is the type for the None object, which is an object that indicates no value. None is the return value of functions that "don't return anything". It is also a common default return value for functions that search for something and may or may not find it; for example, it's returned by re.search when the regex doesn't match, or dict.get when the key has no entry in the dict. You cannot add None to strings or other objects.
One of your variables is None, not a string. Maybe you forgot to return in one of your functions, or maybe the user didn't provide a command-line option and optparse gave you None for that option's value. When you try to add None to a string, you get that exception:
send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)
One of group or SNMPGROUPCMD or V3PRIVCMD has None as its value.
For the sake of defensive programming, objects should be checked against nullity before using.
if obj is None:
or
if obj is not None:
NoneType is simply the type of the None singleton:
>>> type(None)
<type 'NoneType'>
From the latter link above:
None
The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.
In your case, it looks like one of the items you are trying to concatenate is None, hence your error.
It means you're trying to concatenate a string with something that is None.
None is the "null" of Python, and NoneType is its type.
This code will raise the same kind of error:
>>> bar = "something"
>>> foo = None
>>> print foo + bar
TypeError: cannot concatenate 'str' and 'NoneType' objects
In Python
NoneType is the type of the None object.
There is only one such object.
Therefore, "a None object" and "the None object" and
"None" are three equivalent ways of saying the same thing.
Since all Nones are identical and not only equal,
you should prefer x is None over x == None in your code.
You will get None in many places in regular Python
code as pointed out by the accepted answer.
You will also get None in your own code when you
use the function result of a function that does not end with
return myvalue or the like.
Representation:
There is a type NoneType in some but not all versions of Python,
see below.
When you execute print(type(None)), you will get
<type 'NoneType'>.
This is produced by the __repr__ method of NoneType.
See the documentation of repr
and that of
magic functions
(or "dunder functions" for the double underscores in their names) in general.
In Python 2.7
NoneType is a type defined in the
standard library module types
In Python 3.0 to 3.9
NoneType has been
removed
from
module types,
presumably because there is only a single value of this type.
It effectively exists nevertheless, it only has no built-in name:
You can access NoneType by writing type(None).
If you want NoneType back, just define
NoneType = type(None).
In Python 3.10+
NoneType is again a type defined in the
standard library module types,
introduced in order to
help type checkers do their work
In Python, to represent the absence of a value, you can use the None value types.NoneType.None
In the error message, instead of telling you that you can't concatenate two objects by showing their values (a string and None in this example), the Python interpreter tells you this by showing the types of the objects that you tried to concatenate. The type of every string is str while the type of the single None instance is called NoneType.
You normally do not need to concern yourself with NoneType, but in this example it is necessary to know that type(None) == NoneType.
Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>
Python's None object is roughly equivalent to null, nil, etc. in other languages.
If you're getting type None for an object, make sure you're returning in the method. For example:
class Node:
# node definition
then,
def some_funct():
# some code
node = Node(self, self.head)
self.head = node
if you do not return anything from some_func(), the return type will be NoneType because it did not return anything.
Instead, if you return the node itself, which is a Node object, it will return the Node-object type.
def some_func(self):
node = Node(self, self.head)
self.head = node
return node
One of the variables has not been given any value, thus it is a NoneType. You'll have to look into why this is, it's probably a simple logic error on your part.
It's returned when you have for instance print as your last statement in a function instead of return:
def add(a, b):
print(a+ b)
x = add(5,5)
print(x)
print(type(x))
y = x + 545
print(y)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
<class 'NoneType'>
def add(a, b):
return (a+ b)
x = add(5,5)
print(x)
print(type(x))
10
<class 'int'>
555
NoneType is the type of None.
See the Python 2 docs here:
https://docs.python.org/2/library/types.html#types.NoneType
NoneType is type of None. Basically, The NoneType occurs for multiple reasons,
Firstly when you have a function and a condition inside (for instance), it will return None if that condition is not met.
Ex:-
def dummy(x, y): if x > y: return x res = dummy(10, 20) print(res) # Will give None as the condition doesn't meet.
To solve this return the function with 0, I.e return 0, the function will end with 0 instead of None if the condition is not satisfied.
Secondly, When you explicitly assign a variable to a built-in method, which doesn't return any value but None.
my_list = [1,2,3]
my_list = my_list.sort()
print(my_list) #None sort() mutate the DS but returns nothing if you print it.
Or
lis = None
re = lis.something())
print(re) # returns attribute error NonType object has no attribute something

TypeError: unsupported operand type(s) for -: 'str' and 'str'

a'$'
money=1000000;
portfolio=0;
value=0;
value=(yahoostock.get_price('RIL.BO'));
portfolio=(16*(value));
print id(portfolio);
print id(value);
money= (money-portfolio);
'''
I am getting the error:
Traceback (most recent call last):
File "/home/dee/dee.py", line 12, in <module>
money= (value-portfolio);
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Since money is integer and so is portfolio, I cant solve this problem..anyone can help???
value=(yahoostock.get_price('RIL.BO'));
Apparently returns a string not a number. Convert it to a number:
value=int(yahoostock.get_price('RIL.BO'));
Also the signal-to-noise ratio isn't very high. You've lots of (,), and ; you don't need. You assign variable only to replace them on the next line. You can make your code nicer like so:
money = 1000000
value = int(yahoostock.get_price('RIL.BO'));
portfolio = 16 * value;
print id(portfolio);
print id(value);
money -= portfolio;
money and portfolio are apparently strings, so cast them to ints:
money= int( float(money)-float(portfolio) )
As the error message clearly states, both are string, cast with int(var).
Note:
Let's see what can we decude from the error message:
portfolio must be string(str), which means value is also a string. Like this:
>>> 16*"a"
'aaaaaaaaaaaaaaaa'
and apparently you missed to post relevant code because the error message tells you that money is str as well.
I think the problem here is assuming that because you have initialised variables with integer values they will remain as integers. Python doesn't work this way. Assigning a value with = only binds the name to the value without paying any attention to type. For example:
a = 1 # a is an int
a = "Spam!" # a is now a str
I assume yahoostock.getprice(), like many functions that get data from websites, returns a string. You need to convert this using int() before doing your maths.

TypeError: 'int' object is unsubscriptable

In python I get this error:
TypeError: 'int' object is unsubscriptable
This happens at the line:
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
I couldn't find a good definition of unsubscriptable for python anywhere.
for quote in sector[singlestock]:
i+=1
if i < len(sector):
if i==0:
sectorcalc[i][0]= quote[0]
sectorcalc[i][2]= 0
sectorcalc[i][3]= 0
sectorcalc[i][4]= 0
sectorcalc[i][5]= 0
sectorcalc[i][6]= 0
sectorcalc[i][7]= 0
else:
yesterday = sector[singlestock-1][i]
print yesterday
today = quote
print type(today[2])
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
sectorcalc[i][3]= (today[3]/yesterday[3])-1
sectorcalc[i][4]= (today[4]/yesterday[4])-1
sectorcalc[i][5]= (today[5]/yesterday[5])-1
sectorcalc[i][6]= (today[6]/yesterday[6])-1
sectorcalc[i][7]= (today[7]/yesterday[7])-1
What does this error mean?
The "[2]" in today[2] is called subscript.
This usage is possible only if "today"
is a sequence type. Native sequence
types - List, string, tuple etc
Since you are getting an error - 'int' object is unsubscriptable. It means that "today" is not a sequence but an int type object.
You will need to find / debug why "today" or "yesterday" is an int type object when you are expecting a sequence.
[Edit: to make it clear]
Error can be in
sectorcalc[i]
today (Already proved is a list)
yesterday
This is confusing to read:
today = quote
Is today = datetime.date.today()? Why would a date suddenly refer to a quote? Should the variable name be quoteForToday or something more expressive? Same for yesterday. Dividing two dates as you do makes no sense to me.
Since this is a quote, would today and yesterday refer to prices or rates on different days? Names matter - choose them carefully. You might be the one who has to maintain this six months from now, and you won't remember what they mean, either.
Not that the code you wrote is valid, but I can't see why you wouldn't use a loop.
for j in range(2,7):
sectorcalc[i][j] = (today[j]/yesteday[j])-1
instead of
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
sectorcalc[i][3]= (today[3]/yesterday[3])-1
sectorcalc[i][4]= (today[4]/yesterday[4])-1
sectorcalc[i][5]= (today[5]/yesterday[5])-1
sectorcalc[i][6]= (today[6]/yesterday[6])-1
sectorcalc[i][7]= (today[7]/yesterday[7])-1
How to reproduce that error:
myint = 57
print myint[0]
The people who wrote the compiler said you can't do that in the following way:
TypeError: 'int' object is unsubscriptable
If you want to subscript something, use an array like this:
myint = [ 57, 25 ]
print myint[0]
Which prints:
57
Solution:
Either promote your int to a list or some other indexed type, or stop subscripting your int.

Categories

Resources