ValueError:int () 以 10 为基数的无效文字 [英] ValueError: invalid literal for int () with base 10

查看:30
本文介绍了ValueError:int () 以 10 为基数的无效文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

ValueError: 以 10 为基数的 int () 的文字无效.

有什么建议吗?

这是回溯:

回溯(最近一次调用最后一次):文件C:UserskasutajaDesktopEksponentfunktsioonTEST - koopia.py",第 13 行,在 <module> 中如果 int(a) <0:ValueError:int() 的无效文字,基数为 10:'0.3'

每次我输入一个小于 1 但大于 0 的数字时都会出现问题.在这个例子中它是 0.3 .

这是我的代码:

# y = a^x导入时间导入数学导入系统导入操作系统导入子流程导入 matplotlib.pyplot 作为 plt打印(y = a^x")打印 ("")a = input ("请输入'a'")打印 ("")如果 int(a) <0:print ("'a' 为负数,无解")elif int(a) == 1:打印('a'等于1,无解")别的: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('底部')ax.yaxis.set_ticks_position('left')plt.savefig("graph.png")subprocess.Popen('explorer "C:\Users\kasutaja\desktop\graph.png"')def restart_program():python = sys.executableos.execl(蟒蛇,蟒蛇,* sys.argv)如果 __name__ == "__main__":answer = input("重启程序?")如果 answer.strip() 在 "YES yes Yes Yes Y Y".split():restart_program()别的:os.remove("C:\Users\kasutaja\desktop\graph.png")

解决方案

答案:

你的回溯告诉你 int() 接受整数,你试图给出一个小数,所以你需要使用 float():

a = float(a)

这应该会按预期工作:

<预><代码>>>>int(input("输入一个数字:"))输入数字:0.3回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.ValueError:int() 的无效文字,基数为 10:'0.3'>>>浮动(输入(输入一个数字:"))输入数字:0.30.3

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

(请注意,Python 非常擅长将它从您身上抽象出来,例如,大多数其他语言也有双精度浮点数,但您不必担心.从 3.0 开始,Python 也将如果将整数除以它们,则会自动将它们转换为浮点数,因此实际上很容易使用.)

在我们进行回溯之前对答案的先前猜测:

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

<预><代码>>>>int(input("输入一个数字:"))输入数字:-1-1>>>int(input("输入一个数字:"))输入一个数字: - 1回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.ValueError:int() 的无效文字,基数为 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]

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

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

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: invalid literal for int () with base 10.

Any suggestions?

Here's the traceback:

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' 

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 .

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")

解决方案

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

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.

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

这篇关于ValueError:int () 以 10 为基数的无效文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆