简体   繁体   中英

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)

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, ie:

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

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

print(type(z))
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))

you should do a type cast:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM