[英]im experiencing this error when running a program “ValueError: invalid literal for int() with base 10:”
i am attempting to build a composite function calculator, but I'm running into some issues. 我正在尝试构建复合函数计算器,但遇到了一些问题。
import math
xval = input(int("what is the value of X?"))
fval = input(str("what is the value of f?"))
gval = input(str("what is the value of f?"))
this is the bit of code that isn't working. 这是一些无效的代码。 For the "xval" variable i keep on getting the error message
对于“ xval”变量,我不断收到错误消息
ValueError: invalid literal for int() with base 10: 'what is the value of X?'
ValueError:以10为底的int()的无效文字:“ X的值是多少?”
I've looked around online, but I can't find any issues with my code. 我在线上四处看看,但是我的代码找不到任何问题。
You have to first execute input
and then int
to cast the result into an integer number. 您必须先执行
input
,然后执行int
才能将结果转换为整数。
Otherwise you are trying to convert a text into an integer 否则,您将尝试将文本转换为整数
xval = int(input("what is the value of X?"))
In the other lines, the str
is redundant, but is it really what you want? 在其他方面,
str
是多余的,但是它真的是您想要的吗? I mean to me it looks like fval
and gval
should also be numbers. 我的意思是
fval
和gval
应该也是数字。
Ah, and the text for gval should be "what is the value of g " 嗯,gval的文本应该是“ g的值是什么”
Also take in account that int
will convert your inputs to integers, if you need decimal numbers consider using float()
还要考虑到
int
会将输入转换为整数,如果需要十进制数字,请考虑使用float()
Explanation: 说明:
Your original line input(int("what is the value of X?"))
basically does the following steps: 您原始的行
input(int("what is the value of X?"))
基本上执行以下步骤:
input
giving an integer as text (and failing again) and storing your input as a string. input
并给出一个整数作为文本(并再次失败)并将输入存储为字符串。 As a result your variable xval
would be a string (which is not what you want) xval
将是一个字符串(这不是您想要的) Instead, what you want is to first execute input
and convert the value that you type into an integer, so you have to execute: 相反,您想要的是首先执行
input
并将input
的值转换为整数,因此必须执行:
xval = int(input("what is the value of X?"))
Note that if you input a string, then the cast into int()
will fail, you might want to use try
and catch a possible exeption. 请注意,如果输入字符串,则强制转换为
int()
会失败,您可能需要使用try
并捕获可能的示例。
If you are using Python3.x, Python 3.x doesn't evaluate and convert the data type, you have to explicitly convert to int 如果您使用的是Python3.x,则Python 3.x不会评估和转换数据类型,您必须显式转换为int
x = int(input("what is the value of X?"))
If you are using Python2.x, you need to do like this: 如果您使用的是Python2.x,则需要执行以下操作:
x = input("what is the value of X?")
You can then check the type of x using type(x), you will get <type 'int'>
然后可以使用type(x)检查x的类型,您将得到
<type 'int'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.