-3

我怎样才能让它工作?

n = 1234
f = open("file", "r")
while True:
 x=f.readline()
 print "*********************"
 print n%(long(x))
 if n%(long(x))==0:
   print x
else:
 print "..."

我是 python 的菜鸟,我遇到了一个我不明白的错误。我究竟做错了什么?

ValueError: invalid literal for long() with base 10: ''
4

2 回答 2

6
In [104]: long('')
ValueError: invalid literal for long() with base 10: ''

This error is telling you that x is the empty string.

You could be getting this at the end of the file. It can be fixed with:

while True:
    x = f.readline()
    if x == '': break
于 2013-03-19T22:24:45.790 回答
0

块可以是调试此类事情的try/except便捷方式

n = 1234
f = open("file", "r")
while True:
 x=f.readline()
 print "*********************"
 try:                                              # Add these 3 lines
     print n%(long(x))
 except ValueError:                                # to help work out
     print "Something went wrong {!r}".format(x)   # the problem value
 if n%(long(x))==0:
   print x
else:
 print "..."
于 2013-03-19T22:36:54.580 回答