Python input和raw_input的区别

Python inputraw_input的区别

使用inputraw_input都可以读取控制台的输入,但是inputraw_input在处理数字时是有区别的

纯数字输入

当输入为纯数字时

  • input返回的是数值类型,如int,float
  • raw_inpout返回的是字符串类型,string类型

输入字符串为表达式

input会计算在字符串中的数字表达式,而raw_input不会。

如输入 “57 + 3”:

  • input会得到整数60
  • raw_input会得到字符串”57 + 3”

python input的实现

python input的文档,可以看到input其实是通过raw_input来实现的,原理很简单,就下面一行代码:

def input(prompt):
    return (eval(raw_input(prompt)))
备注:
input([prompt])

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.

posted @ 2012-02-15 13:04  SophiaTang  阅读(438)  评论(0编辑  收藏  举报