This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed last month.
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")
Answer:
Your traceback is telling you that int() takes integers, you are trying to give a decimal, so you need to use float():
a = float(a)
This should work as expected:
>>> int(input("Type a number: "))
Type a number: 0.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.3'
>>> float(input("Type a number: "))
Type a number: 0.3
0.3
Computers store numbers in a variety of different ways. Python has two main ones. Integers, which store whole numbers (ℤ), and floating point numbers, which store real numbers (ℝ). You need to use the right one based on what you require.
(As a note, Python is pretty good at abstracting this away from you, most other language also have double precision floating point numbers, for instance, but you don't need to worry about that. Since 3.0, Python will also automatically convert integers to floats if you divide them, so it's actually very easy to work with.)
Previous guess at answer before we had the traceback:
Your problem is that whatever you are typing is can't be converted into a number. This could be caused by a lot of things, for example:
>>> int(input("Type a number: "))
Type a number: -1
-1
>>> int(input("Type a number: "))
Type a number: - 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '- 1'
Adding a space between the - and 1 will cause the string not to be parsed correctly into a number. This is, of course, just an example, and you will have to tell us what input you are giving for us to be able to say for sure what the issue is.
Advice on code style:
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)]
This is an example of a really bad coding habit. Where you are copying something again and again something is wrong. Firstly, you use int(a) a ton of times, wherever you do this, you should instead assign the value to a variable, and use that instead, avoiding typing (and forcing the computer to calculate) the value again and again:
a = int(a)
In this example I assign the value back to a, overwriting the old value with the new one we want to use.
y = [a**i for i in x]
This code produces the same result as the monster above, without the masses of writing out the same thing again and again. It's a simple list comprehension. This also means that if you edit x, you don't need to do anything to y, it will naturally update to suit.
Also note that PEP-8, the Python style guide, suggests strongly that you don't leave spaces between an identifier and the brackets when making a function call.
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.
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
int() casting can't handle string numbers that have decimal points
- example --> int('13.5') will give you error , but int('13') will convert the
string to integer
Why : This considered as explicit casting required by the user as it prevents you from losing information like 0.5 if you read dataset and don't know it's had floating-point numbers
Work Around >
int(Float("13.5"))
A real-world example I faced: where I wanted the numbers as int while int(I["mpg"]) directly didn't work so I used float() then int()
sum([int(float(i["mpg"])) for i in file])//len(file)
so, the question says, we have to sort an array using insertion sort algorithm and print the resulting array after each iteration with numbers separated by space.
please help me understand what is the problem. why it is throwing an error?
input: 1 4 3 5 6 2
def insertionSort2(n, arr):
for i in range(1,n):
small=int(arr[i])
j=i-1
while j>=0 and int(arr[j])>small:
arr[j+1]=arr[j]
j-=1
arr[j+1]=small
print(' '.join(arr))
print('\r')
if __name__ == '__main__':
n = int(input())
arr = input().rstrip().split()
print(' '.join(arr))
insertionSort2(n, arr)
when I printed array in the main function, then the output was:1 4 3 5 6 2
but, when I was trying to print the array in the function insertionSort2
run time error occured.
File "Solution.py", line 30, in <module>
insertionSort2(n, arr)
File "Solution.py", line 19, in insertionSort2
print(' '.join(arr))
TypeError: sequence item 1: expected str instance, int found
The arr is a list of strings at the start of insertionSort. You then take an element and convert it to an int in line 3: small=int(arr[i]).
So small is now an integer and then it assigned into the list arr[j+1]=small.
Which now means that arr contains a mix of strings and integers. The join method is expecting all strings.
I am trying to write a function that takes two integer inputs a and b and returns a random integer on the interval [a,b]. I tried...
from random import randint
a = input("a = ")
b = input("b = ")
print(randint(a,b))
... but I got the following error.
Traceback (most recent call last):
File "/Users/malcolmjonesnz/PycharmProjects/exploratorySurgery/randomIntegerGeneraterOnA,B.py", line 8, in <module>
print(randint(a,b))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/random.py", line 218, in randint
return self.randrange(a, b+1)
TypeError: Can't convert 'int' object to str implicitly
I have played around trying to "explicitly" convert the inputs to strings, but I've just worked myself into a state of confusion because I'm such a beginner.
Any help would be much appreciated!
The program works well for me. Please replace input by values you define in the program, such as a=1 and b = 5.
What version of python are you using? Maybe your print command causes some errors, since the error seems to come from this line?
I'm trying to make the program print smaller numbers than it did previously this error doesnt make any sense as im comparing two lists not an int and a list?
else:
if len(tuple(guessstore)) == 3:
if guessstore[1] > code[1]:
randomnumber2 = random.randint(0,9 < guessstore[1])
elif guessstore[1] < code[1]:
randomnumber2 = random.randint(0,9 > guessstore[1])
Traceback (most recent call last):
File "F:\Further Programming\Assignment3\number2.py", line 153, in <module>
ch2()
File "F:\Further Programming\Assignment3\number2.py", line 82, in ch2
if guessstore[1] > code[1]: #if code is larger than guess print that its larger
TypeError: unorderable types: list() > int()
Please help. I don't know why I'm getting this error
looks like guessstore[1] is a list and code[1] is a int, maybe the error is in how you handle guessstore that make it a list of list, by the code you show, looks like guessstore is a list, if that is the case perhaps you do something like this guessstore+=[[n]] or guessstore.append( [n] ) (where n in a number) that make you guard a list with n in it inside of guessstore, instead do guessstore.append( n ). Or equivalently in how you handle code that make it a list of int, with only that portion of the code that is all of what I can tell.
#integers to be input
n = input('Enter \"n\" trials')
x = input('Enter \"x\" number of succeses')
p = input('Enter the probability \"p\" of success on a single trial')
#Probability Distribution function
def probDist(n, x, p):
q = (1-p)**(n-x)
numerator = math.factorial(n);
denominator = math.factorial(x)* math.factorial(n-x);
C = numerator / denominator;
answer = C*p**x*q;
return answer
# Does this have to come after I define the function? Or does this matter in Python
# Also this part just doesn't work.
dist = probDist(n, x, p);
print(dist);
Here's the error that I get after I run and I input all the values.
Traceback (most recent call last):
line 17, in <module>
dist = probDist(n, x, p);
line 9, in probDist
q = (1-p)**(n-x)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
In Python 3.x, input always returns a string, without applying eval the the user input. Python 2.x input does eval, but that's rarely what you want. If you want an integer, use int(input(...)) and if you want a float (not quite the same as a real number, as it has only limited range!), use float(input). (You should propably catch ValueError to handle the cases where the input is not appropiate; if this is for exercise/education, it's propably okay to leave error handling out for now.)
Does this have to come after I define the function?
Yes.
q = (1-p)**(n-x)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
You have two - operations. One of those two is a mixture of int and str data.
Let's go through each operand.
1 - int
p - result of input(), and therefore a string
n - result of input(), and therefore a string
x - result of input(), and therefore a string
You probably want to do something to convert the results of input() to a proper floating-point value. float() works well for this.