Python中input与raw_input的对比分析

  • Python2

Python 2.x中input()和raw_input()这两个函数均能接受字符串,但raw_input()直接读取控制台的输入(任何类型的输入它都可以接收)。而对于input(),它希望能够读取一个合法的python表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个SyntaxError。

除非对input()有特别的需要,否则应该尽可能使用raw_input()来与用户交互。

  • input()
>>> s = input("input: ")
input:6
>>> type(s)
<type 'int'>
>>> s = input("input: ")
input:"something"
>>> type(s)
<type 'str'>
>>> s = input("input: ")
input:hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
  • raw_input()
>>> s = raw_input("input: ")
input:6
>>> type(s)
<type 'str'>
>>> s = raw_input("input: ")
input:hello
>>> type(s)
<type 'str'>
  • Python3

python3 整合了input()和raw_input(),去除了raw_input(),保留了input()。python3 里input()默认接收到的是str类型。

>>> s = input("input: ")
input:6
>>> type(s)
<class 'str'>
>>> s = input("input: ")
input:hello
>>> type(s)
<class 'str'>

函数语法:input([prompt])

  • if the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOF Error is raised.
  • If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

而对于Python如何实现对文件结束符(EOF)的判断,可以使用

  • sys.stdin
import sys
for line in sys.stdin:
	l = int(line)
	if l != 0:
		print(l)
  • try_except
try:
	while True:
		s = input()
		print(int(s))
except EOFError:
	pass

参考文献:

  1. http://www.runoob.com/python/python-func-input.html
  2. https://blog.csdn.net/qq_35793358/article/details/77506726
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值