在Python 2中之前,该功能input对输入字符串的eval:
Python 2.7.7 (default, Jun 14 2014, 23:12:13)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x=input('Enter x: ')
Enter x: 2
>>> x
2
>>> type(x)
<type 'int'>
>>> x*5
10
和浮子:
>>> x=input('Enter x: ')
Enter x: 2.2
>>> type(x)
<type 'float'>
>>> x*5
11.0
由于它被广泛认为是不明智采取任意代码从用户在应用程序中,此行为已Python 3的
下的Python 3下改变,input总是返回一个字符串:
Python 3.4.1 (default, May 19 2014, 13:10:29)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x=input('Enter x: ')
Enter x: 2.
>>> type(x)
<class 'str'>
哪解释你的结果:
>>> x*5
'2.2.2.2.2.'
如果你想安全有类似的功能在Python 3,你可以在呼叫包input
到ast.literal_eval:
>>> from ast import literal_eval
>>> x=literal_eval(input('Enter x: '))
Enter x: 2.2
>>> x
2.2
>>> type(x)
<class 'float'>
或者,仅仅是用户输入转换为所需的数据类型与int(x)
或float(x)
大概每一个问题的不断声称浮点运算不起作用重复,但投票结束不清楚,因为你甚至没有告诉我们你看到了什么“错误”。 – geoffspear 2014-08-29 17:31:16
或者输入错误的结果是必要的。有可能有一些情况下,python可以正确地做到这一点... – mgilson 2014-08-29 17:31:54
你乘以一个整数* *字符串;某处,您未能转换您的输入。你显示的代码工作正常,这或多或少是完全无益的。阅读http://stackoverflow.com/help/mcve。而你的描述是不正确的; 'rate'必须是字符串,因为此函数*中的输入*被转换。 – jonrsharpe 2014-08-29 17:46:09