Python 2.x 中的 raw_input() 和 input()

来源:互联网 发布:淘宝旺旺怎么加好友 编辑:程序博客网 时间:2024/06/18 10:45

Python 2.x 和 Python 3.x 还是有一点小差别的。比如 input 在 Python 2.x 中有两个函数 raw_input()input()。在 Python 3.x 中,只有一个函数来获取用户输入,这被称为 input(),这相当于 Python 2.7 的 raw_input()

例 1:input()

name = input('Please enter your number: ')print name

命令行 1.1

Please enter your number: 'qq'qq

命令行 1.2

Please enter your number: "qq"qq

命令行 1.3

Please enter your number: qqTraceback (most recent call last):    File "onr.py", line 1, in < module> #onr.py是我的文件名    name = input('Please enter your number: ')  File "< string>", line 1, in < module >NameError: name 'qq' is not defined

命令行 1.4

Please enter your number: 1111

命令行 1.5

Please enter your number: '1+1'1+1

命令行 1.6

Please enter your number: 1+12

例 2:raw_input()

name = raw_input('Please enter your number: ')print name

命令行 2.1

Please enter your number: qqqq

命令行2.2

Please enter your number: '1+1''1+1'

命令行2.3

Please enter your number: 1+11+1

Python 2.x

  • raw_print() 可以直接读取控制台的任何类型输入,并且只会读入您输入的任何内容,返回字符串类型。即可用把控制台所有输入作为字符串看待,并返回字符串类型。
  • input() 能够读取一个合法的 python 表达式,返回数值类型,如int,float。即如果你在控制台输入的字符串必须用单引号或双引号将它括起来,否则会引发 SyntaxError 。

Python 2.7 input 说明文档

Python 3.x

Python 2.x 中的 raw_input() 被重命名为 Python 3.x 中的 input(),所以 Python 3.x 中的 input() 返回类型为字符串类型。同时 Python 2.x 中的 input() 在 Python 3.x 中不再保留。

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

def input(prompt):    return (eval(raw_input(prompt)))

如果要使用 Python 2.x 中的 input(),即需要将用户输入看作 Python 语句,则必须手动操作 eval(input())

原创粉丝点击