ValueError : int ()에 대한 잘못된 리터럴
풀 수있는 프로그램을 작성하고 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'
문제는 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
컴퓨터는 다양한 방식으로 숫자를 저장합니다. 파이썬에는 크게 두 가지가 있습니다. 정수 (ℤ)를 저장하는 정수와 실수 (ℝ)를 저장하는 부동 소수점 수. 필요한 사항에 따라 올바른 것을 사용해야합니다.
(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
참고URL : https://stackoverflow.com/questions/13861594/valueerror-invalid-literal-for-int-with-base-10
'programing tip' 카테고리의 다른 글
런타임에 node.js 버전 가져 오기 (0) | 2020.11.28 |
---|---|
eval (parse (…))의 위험은 구체적으로 무엇입니까? (0) | 2020.11.28 |
arduino 환경에서 라이브러리를 어떻게 제거합니까? (0) | 2020.11.28 |
Golang은 가변 기능을 지원합니까? (0) | 2020.11.28 |
redux에서 AJAX 요청을 만드는 방법 (0) | 2020.11.28 |