-3

How do I get this to work?

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 "..."

I'm a noob in python and I'm getting an error I don't understand. What am I doing wrong?

ValueError: invalid literal for long() with base 10: ''
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
cerber
  • 1
  • 1
  • 1
  • 7

2 Answers2

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
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

A try/except block can be a handy way to debug things like this

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 "..."
John La Rooy
  • 295,403
  • 53
  • 369
  • 502