Python中input()函数与raw_input()函数的区别

本文详细介绍了Python中的input()和raw_input()函数的区别及用法,包括它们在Python 2.x和Python 3.x中的变化。重点说明了在不同版本中如何正确地获取用户输入。

input()函数和raw_input()函数都是Python内建函数

Python 2.x中raw_input()函数帮助文档

Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

Python 2.x中input()函数帮助文档

Help on built-in function input in module __builtin__:

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).
raw_input()函数接受用户输入时把输入作为字符串返回,input()函数期望用户输入正确的数据类型,其实input()函数是借用raw_input()函数来实现的,在Python 2.x中最好直接使用raw_input()函数来处理用户的输入

>>> name=input("what is your name? ")
what is your name? Clef #期待输入字符串,并且同时要输入引号
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Clef' is not defined
>>> name=input("what is your name? ")
what is your name? 'Clef'
>>> name
'Clef'
>>> name=raw_input("what is your name? ") #用raw_input()函数来接受用户输入的时候,就不用同时输入引号
what is your name? Clef
>>> name
'Clef'
Python 3.0中已经没有raw_input()函数帮助文档,因为在Python 3.x中已经没有raw_input()函数,已经把原来在Python 2.x中的raw_input()函数重命名为了input()函数

Python 3.0中input()函数帮助文档

Help on built-in function input in module builtins:

input(...)
    input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值