刚学python出现个小问题:invalid literal for int() with base 10:

a=int(input())
输入12.3
报错,请问问题出在哪里?

异常出现的直接原因即是,对于一个浮点数的字符('12.3'),直接使用 int 进行强制类型转换:
>>> int('1.5')
ValueError: invalid literal for int() with base 10: '1.5'>>> int('1.0')
ValueError: invalid literal for int() with base 10: '1.0'1234
也即,使用 int 对一个字符类型的数据进行强制类型转换时,要求输入的字符类型只能为整数,不能为浮点数。
如果非要整数浮点数一起输入,或者可以换成下面做法
a=float(input())
这样,不管你输的是整数还是浮点都可以通过.可是,切记,其它字符比如abc之类的,还是不行哦!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-03-30

这是进入解释器了,不进入解释器直接在命令行里输入python "F:\python\textweb.py"就可以了。

Python(英语发音:/ˈpaɪθən/), 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年,Python 源代码同样遵循 GPL(GNU General Public License)协议。

Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。常见的一种应用情形是,使用Python快速生成程序的原型(有时甚至是程序的最终界面)。

然后对其中有特别要求的部分,用更合适的语言改写,比如3D游戏中的图形渲染模块,性能要求特别高,就可以用C/C++重写,而后封装为Python可以调用的扩展类库。需要注意的是在您使用扩展类库时可能需要考虑平台问题,某些可能不提供跨平台的实现。

本回答被网友采纳
第2个回答  2018-02-01
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 
注意:如果给定的X不是一个数字,那么必须是表示指定进制的整数的字符串,字节或者字节数组的实例。

  也就是说你采用输入的方式,获得的字符串只有表示整数的时候才能用int(string)来转换
  
  如下是有效的输入:
  
  int(12.3)
  int('12')

第3个回答  2014-08-09
因为int函数不能接受字面值为浮点数的字符串,即当执行int('12.3')的时候就会报错
这种时候需要要用float转化成浮点数, a = float(input())追问

我看给小孩子看的python上有这么一段:如果你希望用户输入的数总是整数(而不是小数),可以用int()来转换,例如:
response=raw_input('How many students are in your class: ')
number=int(response)

效果不是跟a=int(input())一样吗。

追答

那是python2,学python请注意版本。。。

第4个回答  2018-02-01
你定义的是int整型,而输入的12.3是float浮点型,所以会造成数值类型错误,改成a=float(input()),或者不加类型定义,直接a = input()
相似回答