我已經寫了一個程序,讀取一個由10對數字組成的文件,然後將這兩個文件分開,產生混合部分,然後將其添加到原始文檔。但是,我希望錯誤消息與對的順序相同。我的文件包括:追加到文件和消息出現在錯誤的順序python
66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 21
,我的計劃是這樣的:
from fractions import gcd
x=0
y=0
global index
index=0
wordlist=[]
with open('topheavy.txt','r') as f:
for line in f:
for word in line.split():
print(word)
wordlist.append(word)
print (wordlist)
print (len(wordlist))
def mixedfraction():
global index
while index<len(wordlist):
global x
global y
x=wordlist[index]
y=wordlist[index+1]
neg=False
with open ('topheavy.txt','a') as g:
try:
float(x)
except ValueError:
g.write ('x is not a number.\n')
global index
index+=2
mixedfraction()
try:
float(y)
except ValueError:
g.write ('y is not a number.\n')
global index
index+=2
mixedfraction()
#the above code checks if its a number.
x=int(x)
y=int(y)
orx=0
ory=0
orx+=x
ory+=y
if x==0 or y==0:
with open ('topheavy.txt','a') as g:
g.write ('you cant divide by 0!\n')
global index
index+=2
mixedfraction()
#this is to make sure you dont get a divide by 0 error.
if x<0 and not y<0:
neg=True
x*=-1
elif y<0 and not x<0:
neg=True
y*=-1
if 1==1:
xy=(x//y)
modxy=(x%y)
modxy=round(modxy,0)
xy=round(xy,0)
y=round(y,0)
xdivisor=gcd(modxy, y)
modxy//=xdivisor
y//=xdivisor
#the above 3 lines reduce the fraction, as do the similar 3 lines in the other bit of code.
with open ('topheavy.txt','a') as g:
if modxy!=0 and xy!=0:
b= ('{}/{}={} and {}/{}\n'.format(orx,ory,xy, modxy, y ))
if neg==True:
b=(' {}/{}=-{} and {}/{}\n'.format(orx,ory,xy, modxy, y ))
g.write (b)
elif modxy==0 and xy!=0:
b= ('{}/{}={} \n'.format(orx,ory,xy))
if neg==True:
b=(' {}/{}=-{} \n'.format(orx,ory,xy))
g.write (b)
elif xy==0:
b=('{}/{}={}/{} \n'.format(orx,ory,modxy, y))
if neg==True:
b=('{}/{}=-{}/{} \n'.format(orx,ory,modxy, y))
g.write (b)
#this if clause stops the program from saying '5 and 0/5' or a similar thing.
global index
index=index+2
mixedfraction()
當我運行它,我得到這個:
66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 2166/556=33/278
-56/78=-28/39
43/76=43/76
6/5=1 and 1/5
98/76=1 and 11/38
4/2=2
66/54=1 and 2/9
98/21=4 and 2/3
x is not a number.
98/3=32 and 2/3
you cant divide by 0!
0/5=32 and 2/3
的 '你不能除以0' 消息在錯誤的地方,'x不是數字'的信息也是如此。我不知道如何讓他們去正確的地方。然後在最後添加一些奇怪的隨機行,這不應該在那裏。我已經找遍了,找不到解決方案。謝謝你的幫助。
我要的是:
66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
66/556=answer
-56/78=answer
43/76=answer
you cant divide by 0!
6/5=answer
x is not a number!
98/76=answer
4/2= answer
66/54=answer
請提供您期望的例子。 – Alderven 2014-10-31 12:35:54
我加了。謝謝 – Sawyer 2014-10-31 13:05:27
爲什麼你不能劃分0 \ 5?只有在5 \ 0的情況下才能分割。 – Alderven 2014-10-31 13:12:05