0

Hello,

I have problem with arithmetic in python when use it like this code

#!/usr/bin/python

AA = open("a.txt").readline()
print AA
BB = 100
print BB + AA

Appear to me this error :

Traceback (most recent call last):
File "aa.py", line 6, in ?
print BB + AA
TypeError: unsupported operand type(s) for +: 'int' and 'str'


when delete the arithmetic line "print BB + AA" or change it to "print BB + 50"
the code working good
20

150

Why not confess with number when i get it from file ?
And the same error if I get the number from another python file like modul :

import file
print BB + file.number

any idea ?

Thanks

2
Contributors
4
Replies
7
Views
7 Years
Discussion Span
Last Post by zoro007
0

The number from file looks like number but it is string until you transform it to real number with int(stringnumber) or float(stringnumber) You can see the information, that operand is wrong type from the error message:

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

You can confirm it by replacing your print:

print type(AA),repr(AA)

Edited by pyTony: n/a

0

You can confirm it by replacing your print:
Python Syntax (Toggle Plain Text)

1.
print type(AA),repr(AA)

I did that and still appear that error

Any solution ?

2

int or float:

open('testfile.txt','w').write(str(1234))
print int(open('testfile.txt').read())+20
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.