use*_*162 64 python python-3.x
我编写了一个程序来解决y = a^x
,然后将其投影到图表上.问题是每当a < 1
我收到错误时:
ValueError:具有基数10的int()的无效文字.
有什么建议?
这是追溯:
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'
Run Code Online (Sandbox Code Playgroud)
每次我放一个小于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")
Run Code Online (Sandbox Code Playgroud)
Gar*_*tty 70
你的回溯告诉你int()
带整数,你试图给出一个小数,所以你需要使用float()
:
a = float(a)
Run Code Online (Sandbox Code Playgroud)
这应该按预期工作:
>>> 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
Run Code Online (Sandbox Code Playgroud)
计算机以各种不同的方式存储数字.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'
Run Code Online (Sandbox Code Playgroud)
在-
和之间添加空格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)]
Run Code Online (Sandbox Code Playgroud)
这是一个非常糟糕的编码习惯的例子.你在一次又一次地复制某些东西是错误的.首先,您使用int(a)
了很多次,无论您在何处执行此操作,都应该将值赋给变量,而是使用它来避免一次又一次地键入(并强制计算机计算)该值:
a = int(a)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我将值赋值回来a
,用我们想要使用的新值覆盖旧值.
y = [a**i for i in x]
Run Code Online (Sandbox Code Playgroud)
这段代码产生的结果与上面的怪物相同,没有大量的反复写出相同的东西.这是一个简单的列表理解.这也意味着如果你编辑x
,你不需要做任何事情y
,它会自然更新以适应.
另请注意,PEP-8(Python样式指南)强烈建议您在进行函数调用时不要在标识符和括号之间留空格.
Le *_*oid 24
正如Lattyware所说,Python2和Python3之间存在差异导致此错误:
使用Python2,int(str(5/2))
为您提供2.使用Python3,同样的结果为您提供:ValueError:基数为10的int()的无效文字:'2.5'
如果你需要转换一些可能包含float而不是int的字符串,你应该总是使用以下丑陋的公式:
int(float(myStr))
Run Code Online (Sandbox Code Playgroud)
作为float('3.0')
并float('3')
给你3.0,但int('3.0')
给你错误.
a
在输入时进行验证可能更好.
try:
a = int(input("Enter 'a' "))
except ValueError:
print('PLease input a valid integer')
Run Code Online (Sandbox Code Playgroud)
这可以转换a
为int,因此可以确保它是所有以后使用的整数,或者它处理异常并提醒用户
归档时间: |
|
查看次数: |
412068 次 |
最近记录: |