Python ValueError:int () 以 10 为基数的无效文字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13861594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ValueError: invalid literal for int () with base 10
提问by user1901162
I wrote a program to solve y = a^xand then project it on a graph. The problem is that whenever a < 1I get the error:
我编写了一个程序来解决y = a^x,然后将其投影到图形上。问题是每当a < 1我收到错误时:
ValueError: invalid literal for int () with base 10.
ValueError:int () 以 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 .
每次我输入一个小于 1 但大于 0 的数字时都会出现问题。对于这个例子,它是 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")
采纳答案by Gareth Latty
Answer:
回答:
Your traceback is telling you that int()takes integers, you are trying to give a decimal, so you need to use float():
您的回溯告诉您int()需要整数,您正在尝试给出小数,因此您需要使用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.
计算机以各种不同的方式存储数字。Python有两个主要的。存储整数 (?) 的整数和存储实数 (?) 的浮点数。您需要根据需要使用正确的方法。
(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.)
(请注意,Python 非常擅长将其抽象出来,例如,大多数其他语言也有双精度浮点数,但您不必担心。从 3.0 开始,Python 也会自动转换整数如果将它们分开,则浮动,因此实际上很容易使用。)
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 1will 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.
在-和之间添加空格1将导致字符串无法正确解析为数字。当然,这只是一个例子,您必须告诉我们您提供了什么意见,以便我们能够确定问题是什么。
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:
这是一个非常糟糕的编码习惯的例子。你一次又一次地复制某些东西的地方是错误的。首先,您使用int(a)了很多次,无论您在哪里执行此操作,您都应该将值分配给一个变量,然后使用它,避免一次又一次地键入(并强制计算机计算)该值:
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.
在这个例子中,我将值分配回a,用我们想要使用的新值覆盖旧值。
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.
这段代码产生与上面的怪物相同的结果,而无需一次又一次地写出大量相同的东西。这是一个简单的列表理解。这也意味着,如果您编辑x,则无需对 执行任何操作y,它自然会更新以适应。
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.
回答by dm03514
It might be better to validate aright when it is input.
最好在a输入时进行验证。
try:
a = int(input("Enter 'a' "))
except ValueError:
print('PLease input a valid integer')
This either casts ato an int so you can be assured that it is an integer for all later uses or it handlesthe exception and alerts the user
这要么转换a为 int,以便您可以确保它是所有以后使用的整数,要么处理异常并提醒用户
回答by Le Droid
As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:
正如 Lattyware 所说,导致此错误的 Python2 和 Python3 之间存在差异:
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'
使用 Python2,int(str(5/2))给你 2。使用 Python3,同样给你: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:
如果您需要转换一些可能包含 float 而不是 int 的字符串,您应该始终使用以下丑陋的公式:
int(float(myStr))
As float('3.0')and float('3')give you 3.0, but int('3.0')gives you the error.
Asfloat('3.0')并float('3')给你 3.0,但int('3.0')给你错误。

