[python] ValueError: invalid literal for int () with base 10

I wrote a program to solve y = a^x and then project it on a graph. The problem is that whenever a < 1 I get the error:

ValueError: invalid literal for int () with base 10.

Any suggestions?

Here's the traceback:

Traceback (most recent call last): 
   File "C:\Users\kasutaja\Desktop\EksponentfunktsioonTEST - koopia.py", line 13, in <module> 
   if int(a) < 0: 
ValueError: invalid literal for int() with base 10: '0.3' 

The problem arises every time I put a number that is smaller than one, but larger than 0. For this example it was 0.3 .

This is my code:

#  y = a^x

import time
import math
import sys
import os
import subprocess
import matplotlib.pyplot as plt
print ("y = a^x")
print ("")
a = input ("Enter 'a' ")
print ("")
if int(a) < 0:
    print ("'a' is negative, no solution")
elif int(a) == 1:
    print ("'a' is equal with 1, no solution")
else:
    fig = plt.figure ()
    x = [-2,-1.75,-1.5,-1.25,-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1,1.25,1.5,1.75,2]
    y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
            int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
            int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
            int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]


    ax = fig.add_subplot(1,1,1)
    ax.set_title('y = a**x')
    ax.plot(x,y)
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    ax.spines['left'].set_smart_bounds(True)
    ax.spines['bottom'].set_smart_bounds(True)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')


    plt.savefig("graph.png")
    subprocess.Popen('explorer "C:\\Users\\kasutaja\\desktop\\graph.png"')

def restart_program(): 
    python = sys.executable
    os.execl(python, python, * sys.argv)

if __name__ == "__main__":
    answer = input("Restart program? ")
    if answer.strip() in "YES yes Yes y Y".split():
        restart_program()
    else:
        os.remove("C:\\Users\\kasutaja\\desktop\\graph.png")

This question is related to python python-3.x

The answer is


You've got a problem with this line:

while file_to_read != " ":

This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.

Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.


I found a work around. Python will convert the number to a float. Simply calling float first then converting that to an int will work: output = int(float(input))


I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:

\x00\x31\x00\x0d\x00

To counter this, I did:

countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)

...where fields is a list of csv values resulting from splitting the line.


The following are totally acceptable in python:

  • passing a string representation of an integer into int
  • passing a string representation of a float into float
  • passing a string representation of an integer into float
  • passing a float into int
  • passing an integer into float

But you get a ValueError if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, as @katyhuff points out above, you can convert to a float first, then to an integer:

>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5

I was getting similar errors, turns out that the dataset had blank values which python could not convert to integer.


As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:

With Python2, int(str(5/2)) gives you 2. With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'

If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:

int(float(myStr))

As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.


The reason you are getting this error is that you are trying to convert a space character to an integer, which is totally impossible and restricted.And that's why you are getting this error.enter image description here

Check your code and correct it, it will work fine


This seems like readings is sometimes an empty string and obviously an error crops up. You can add an extra check to your while loop before the int(readings) command like:

while readings != 0 | readings != '':
    global count
    readings = int(readings)

Pythonic way of iterating over a file and converting to int:

for line in open(fname):
   if line.strip():           # line contains eol character(s)
       n = int(line)          # assuming single integer on each line

What you're trying to do is slightly more complicated, but still not straight-forward:

h = open(fname)
for line in h:
    if line.strip():
        [int(next(h).strip()) for _ in range(4)]     # list of integers

This way it processes 5 lines at the time. Use h.next() instead of next(h) prior to Python 2.6.

The reason you had ValueError is because int cannot convert an empty string to the integer. In this case you'd need to either check the content of the string before conversion, or except an error:

try:
   int('')
except ValueError:
   pass      # or whatever

I had hard time figuring out the actual reason, it happens when we dont read properly from file. you need to open file and read with readlines() method as below:

with open('/content/drive/pre-processed-users1.1.tsv') as f:
    file=f.readlines()

It corrects the formatted output


Just for the record:

>>> int('55063.000000')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'

Got me here...

>>> int(float('55063.000000'))
55063.0

Has to be used!


This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input(). Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling enter image description here

So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.


I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.

Something like this should work:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

your answer is throwing errors because of this line

readings = int(readings)
  1. Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.

Please test this function (split()) on a simple file. I was facing the same issue and found that it was because split() was not written properly (exception handling).


The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.


So if you have

floatInString = '5.0'

You can convert it to int with floatInInt = int(float(floatInString))


It might be better to validate a right when it is input.

try:
  a = int(input("Enter 'a' "))
except ValueError:
  print('PLease input a valid integer')

This either casts a to an int so you can be assured that it is an integer for all later uses or it handles the exception and alerts the user


    readings = (infile.readline())
    print readings
    while readings != 0:
        global count
        readings = int(readings)

There's a problem with that code. readings is a new line read from the file - it's a string. Therefore you should not compare it to 0. Further, you can't just convert it to an integer unless you're sure it's indeed one. For example, empty lines will produce errors here (as you've surely found out).

And why do you need the global count? That's most certainly bad design in Python.


I got into the same issue when trying to use readlines() inside for loop for same file object... My suspicion is firing readling() inside readline() for same file object caused this error.

Best solution can be use seek(0) to reset file pointer or Handle condition with setting some flag then create new object for same file by checking set condition....