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)的判断,可以使用

  • 1 sys.stdin
import sys
for line in sys.stdin:
    l = int(line)
    if l != 0:
        print(l)
  • 2 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

猜你喜欢

转载自blog.csdn.net/Jonms/article/details/79702425
今日推荐