Search code examples
pythonmath

Simple math addition


so I just want to do some simple math addition get number from the first file ( let's say it's 1) and number from the second file ( let's say it's 2) so what I'm getting is 12, not 3 I would really appreciate the help.

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)

Solution

  • The variables z and b are likely str types, and the + operator is defined on str types as concatenation. You can cast the two variables as integers and they should add as you expect, i.e.:

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

    To illustrate this, you can always print out the type of a variable:

    print(type(z))