ValueError:以 10 为底的 int () 的无效文字

2022-01-31 00:00:00 python python-3.x

问题描述

我写了一个程序来解决y = a^x,然后把它投影到一个图上.问题是每当 a <1 我得到错误:

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: int () 以 10 为底的无效文字.

ValueError: invalid literal for int () with base 10.

有什么建议吗?

这是回溯:

Traceback (most recent call last): 
   File "C:UserskasutajaDesktopEksponentfunktsioonTEST - koopia.py", line 13, in <module> 
   if int(a) < 0: 
ValueError: invalid literal for int() with base 10: '0.3' 

每次我输入一个小于 1 但大于 0 的数字时都会出现问题.对于本示例,它是 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 .

这是我的代码:

#  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():

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

计算机以各种不同的方式存储数字.Python有两个主要的.存储整数 (ℤ) 的整数和存储实数 (ℝ) 的浮点数.您需要根据自己的需要使用正确的.

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 非常擅长从您那里抽象出来,例如,大多数其他语言也有双精度浮点数,但您不必担心.从 3.0 开始,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.)

您的问题是您输入的任何内容都无法转换为数字.这可能是由很多原因造成的,例如:

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'

-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.

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) 很多次,无论您在哪里执行此操作,都应该将值分配给变量,并使用它来代替,避免输入(并强制计算机计算)一次又一次的价值:

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)

在本例中,我将值分配回 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]

这段代码产生了与上面的怪物相同的结果,而无需大量地一次又一次地写出相同的东西.这是一个简单的列表理解.这也意味着如果你编辑x,你不需要对y做任何事情,它自然会更新以适应.

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.

另请注意,PEP-8,Python 风格指南,强烈建议在制作时不要在标识符和括号之间留空格函数调用.

相关文章