Keep getting error when using += operation between two variables - Python - python

I currently have a bit of code that adds a certain amount of points to a plyers score:
points = 5
player1 = 0
float(points)
float(player1)
player1 += points
points = 0
The problem is when I run this I get this error:
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
At first, I thought it had to do with the data types of the variables, points and player1 but I have a float function right before it. Also just for debugging purposes I wrote a bool statement print(bool(float(var))) to check if it was floating correct and it wasn't. The points variable floated correctly but it was saying that player1 was not a float. Any ideas on why this is happening?

If you are reading user input, you need to assign the result of float to the variable.
points = float(points) # convert existing string, or use float(input())
player1 = float(player1)

First of all, I was not able to reproduce the error, meaning I executed your code and did not get the error.
Second: When you cast a variable as: float(points) you must save the casting in a variable (or update the previous one).
points = float(points)
Note: in your case, you don't need to cast the variable to float because you are using only int values.

Related

why dose python code 'print(np.array([1355742581.0])[0] < torch.LongTensor([1355742616.0])[0])' output False?

As described in the title, when comparing two timestamp using the following python code, I got an unexpected result, which should be True instead of Fasle, can anyone help explain this problem? Many thanks!
print(np.array([1355742581.0])[0] < torch.LongTensor([1355742616.0])[0])
It seems that when comparing "integer tensor" and "float value other than tensor", PyTorch forcibly converts both to float32. In other words, the comparison you made is implicitly converted as follows.
torch.FloatTensor([1355742581.0]) < torch.FloatTensor([1355742616.0])
# tensor([False])
The reason why this comparison is False is because both numbers are too large to be represented as float32, so they are rounded.
torch.FloatTensor([1355742581.0]).item() # 1355742592.0
torch.FloatTensor([1355742616.0]).item() # 1355742592.0
(If you don't understand why this is happening, please research about floating-point numbers.)
As evidence that this problem is due to precision, the result will be flipped if you add a number that is added to the upper bits.
np.array([1355742581.0])[0] < torch.LongTensor([1355742616.0 + 128])[0]
# tensor(True)
To avoid this problem, either make the right side explicitly DoubleTensor or make the left side DoubleTensor.
np.array([1355742581.0])[0] < torch.LongTensor([1355742616.0]).to(torch.float64)[0]
# tensor(True)
torch.DoubleTensor(np.array([1355742581.0]))[0] < torch.LongTensor([1355742616.0])[0]
# tensor(True)

math.sqrt results in TypeError:'float' object cannot be interpreted as an integer

I'm doing a homework assignment and want to fully train all the classes to what they are expected to do. I came across this TypeError which was really bugging me around.
This is for a little kids' test of health evaluation.
I've tried google, but that just gave me one big blob of code,
and I've tried deleting the Power class and of course, gave me an error.
The main loop(not finished):
pd = Power()
num = pd.calc_num()
cir_num = int(math.sqrt(num))**2
circles = []
filled = 0
while True:
for i in range(math.sqrt(cir_num)-1):
for j in range(math.sqrt(cir_num)-1):
c = Circle(frame, cir_num)
circles.append(c)
##drawing
for c in circles:
if c.stage == 'empty':
c.draw_empty()
elif c.stage == 'filled':
c.draw_filled()
avar = 0
for c in circles:
avar += c.num2
filled += avar
The definition of the power class is:
like there is a number, and there is a function that takes 2 to the power of... the number.
The circle class is that there is a button. If the button stage is 'empty', I will draw the button with an empty circle. If a button with an empty circle is clicked, the button will have a filled circle that won't do anything.
This is the error message:
Traceback (most recent call last):
File "C:/Users/roche/Documents/assignment.py", line 47, in <module>
for i in range(math.sqrt(cir_num)-1):
TypeError: 'float' object cannot be interpreted as an integer
And the tkinter size is weird:
root.geometry('750x750+0+0')
gives me a vertical rectangle and I was expecting a square window.
Thanks!
You twice use the expression
range(math.sqrt(cir_num)-1)
The result of math.sqrt is a float value, so you are trying to get the range of a float value. As the documentation for range states,
The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method).
So if you really want to use range and math.sqrt together, you must convert the float to an int. This is probably what you want:
range(int(math.sqrt(cir_num))-1)
As one of the comments implies, range demanding an integer makes sense. If you ask for range(math.sqrt(5)), how is the program to loop from 0 to 2.2361? There is no obvious meaning for that, so Python requires to loop over only integer values. The numpy module does have the arange function and the linspace function, which can handle non-integer values, but the meaning of the ranges has been somewhat changed from Python's range.
You are using range to mean much what it means in natural language, which is more or less a segment of the real number line, as in "temperature in the range 37.2C to 38.6C". But that is not what range() means in Python. In Python it means a bunch of contiguous integers. That is why you are getting complaints about the float you are calling it with.

Unsupported Operand Error generated from custom factorial function

f = input("Enter the number to be squared : ")
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(f))
I am trying to get the factorial of the input number
When running the code I receive the following error:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
You have to typecast your input into float or integer for it to be accepted on your mathematical equation. You can even place that in a while loop together with the try: and except ValueError: to cover the error in entry or give messages when your user does not satisfy the type you want your f variable. You can read the documentation for more info.
f = int(input("Enter the number to be squared : "))
OR
f = float(input("Enter the number to be squared : "))
On your original code f would take any a string value even if the user inputs the number 2 for example. So when you call the function that solves your factorial, it will return an error, because of course, you cannot do factorial notation on a string.
You forgot closing parenthesis ')' at the parenthesis end.
The data type of variable 'f' must be an integer and you are passing a string. As 'input' assigns string data type by default to the variable.
Make the following changes:
f = int(input("Enter the number to be squared : "))
print(factorial(f))
to lines 1 and the last line respectively.
The first problem that I see is with your data types. You will need to convert f to either an integer or a float so that it can be used in the mathematical operations in your function. You may also want to include some exception handling in case the user enters something other than a number.
You can convert the type by using int(f) or float(f)
As another commenter mentioned, you are also missing a parenthesis at the end of print(factorial(f).
If you make these changes your code should run.

Python function error : '<' not supported between types 'str' and 'int'

I am working on repeats classification project. I am calculating time lapse in between a repeat and fresh mail in days. I want to apply a function on this time lapse which states whether it is a fresh mail or repeat mail.
function:
days = df['days_difference']
if(days<30):
return 'repeat'
else:
return 'fresh'
I am getting error: not supported between instances of 'str' and 'int'
'days_difference' column contains integer values along with None values.
looking for a solution !
That basically means that your 'days ' variable is a string. You can not compare strings with integers using "<".
Try :
...
if(int(days)<30):
...
One recommendation which you should consider, always perform a search with the exact error you get from python, and often times you get your response within 0.1 ms.
In your case, you are comparing an integer value (let's say 2) to a string value, which happens to be '2') and python does not understand.
You can compare `int(days)' and 30 like:
if(int(day) < 30):
return 'repeat'
else:
return 'fresh'
The error is self-explaining :
Python function error : '<' not supported between types 'str' and 'int'
This is caused by a comparison of str and int types, which is invalid in Python 3 (although it's ok in Python 2).
Example :
result = '20' > 10 # In Python 3, this is illegal and will raise an exception
In your case, the error is most probably caused by the test if(days<30):. Your dataframe probably contains str values. You may need to convert them to int before trying to compare to another value:
days = int(df['days_difference'])
if(days<30):
return 'repeat'
else:
return 'fresh'

Adding numbers in a list gives TypeError: unsupported operand type(s) for +: 'int' and 'str'

I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:
Traceback (most recent call last):
File "Calculator.py", line 17, in <module>
addition = sum(inputs)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
My code is:
#declare variables
inputs = []
done = False
#while loop for inputting numbers
while done == False:
value = raw_input()
#escape loop if user enters done
if value == "Done":
print inputs
done = True
else:
inputs.append(value)
addition = sum(inputs)
print addition
raw_input returns strings, not numbers. sum operates only on numbers.
You can convert each item to an int as you add it to the list: inputs.append(int(value)). If you use float rather than int then non-integer numbers will work too. In either case, this will produce an error if the user enters something that is neither Done nor an integer. You can use try/except to deal with that, but that's probably out of the scope of this question.
When using raw_input() you're storing a string in value. Convert it to an int before appending it to your list, e.g.
inputs.append( int( value ) )

Categories

Resources