我写了一个程序来解决y = a^x
,然后把它投射到一个图形上。问题是,每当a < 1
时,我就会出现错误。
ValueError: int ()的无效文字,基数是10。
有什么建议吗?
这里是回溯。
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'
每当我输入一个小于1,但大于0的数字时,问题就会出现,在这个例子中是0.3。
这是我的代码。
# 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")
你的回溯告诉你,int()
取的是整数,你想给的是小数,所以你需要使用float()
。
a = float(a)
这应该能达到预期效果。
>>> 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
计算机以各种不同的方式存储数字。Python有两种主要的方式。整数,用于存储整数(ℤ),和浮点数,用于存储实数(ℝ)。你需要根据你的要求来使用正确的一种。
(注意,Python 在抽象化这一点上做得很好,大多数其它语言也有双精度浮点数,例如,但你不需要担心这个问题。从3.0开始,如果你除以整数,Python也会自动将其转换为浮点数,所以它实际上非常容易操作)。
你的问题是,无论你输入的是什么,都不能被转换成数字。这可能是由很多事情造成的,例如:。
>>> 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'
在"-"和 "1 "之间添加空格会导致字符串不能被正确解析为数字。当然,这只是一个例子,你必须告诉我们你的输入是什么,我们才能确定问题出在哪里。
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)]
这是一个非常糟糕的编码习惯的例子。你一次又一次地复制一些东西,这是不对的。首先,你多次使用int(a)
,无论你在哪里这样做,你都应该把这个值分配给一个变量,然后用它来代替,避免一次又一次地输入(并迫使计算机计算)这个值。
a = int(a)
在这个例子中,我把这个值赋给了a
,用我们要使用的新值覆盖了旧值。
y = [a**i for i in x]
这段代码产生的结果与上面的怪物相同,而不需要反复写出同样的东西。这是一个简单的[list comprehension][1]。这也意味着,如果你编辑x
,你不需要对y
做任何事情,它自然会更新以适应。
正如Lattyware所说,Python2和Python3之间有一个区别,导致了这个错误。
在Python2中,int(str(5/2))
给你2。
而在Python3中,同样的错误会出现。ValueError: invalid literal for int() with base 10: ' 2.5'
如果你需要转换一些可能包含float而不是int的字符串,你应该总是使用下面这个丑陋的公式。
int(float(myStr))
因为float('3.0')
和float('3')
可以得到3.0,但int('3.0')
会出现错误。