简单的数学加法

时间:2019-10-09 02:20:43

标签: python math

所以我只想做一些简单的数学加法 从第一个文件中获取数字(假设它是1) 和第二个文件中的数字(假设是2) 所以我得到的是12,而不是3 我真的很感谢您的帮助。

myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)

myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))

with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)

with open('liczba1.txt', "r") as file:
z = file.read(1)

with open('liczba22.txt', "r") as fil:
b = fil.read(1)

print(z + b)

3 个答案:

答案 0 :(得分:2)

变量zb可能是str类型,并且+运算符在str类型上被定义为串联。您可以将这两个变量转换为整数,并且它们应该按预期添加,即:

print(int(z) + int(b))

为了说明这一点,您总是可以打印出变量的类型:

print(type(z))

答案 1 :(得分:0)

myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)

myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))

with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)

with open('liczba1.txt', "r") as file:
z = file.read(1)

with open('liczba22.txt', "r") as fil:
b = fil.read(1)

print(int(z) + int(b))

答案 2 :(得分:0)

您应该进行类型转换:

total = int(z) + int(b)
print(total)