zzliu

python2和python3的input是不同的

python3的input

对于python3,只有input,官方文档里是这样描述的

def input(*args, **kwargs): # real signature unknown
    """
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
    """
    pass



意思就是:读取一个字符串并输入,舍弃结尾的换行符 ```python a = input() print(a, type(a))

b = input()
print(b, type(b))

<br>
控制台输出结果
```python
hello
hello <class \'str\'>
123
123 <class \'str\'>


python2的input

python2有input和raw_input两种输入

input

a = input()
print(a, type(a))

b = input()
print(b, type(b))


控制台输出结果
123
(123, <type \'int\'>)
hello
Traceback (most recent call last):
  File "D:/input_test/test.py", line 11, in <module>
    b = input()
  File "<string>", line 1, in <module>
NameError: name \'hello\' is not defined


报错了!这是因为input是获取原始的输入内容,也就是说,输入什么,就会得到什么

官方文档是这样描述的

def input(prompt=None): # real signature unknown; restored from __doc__
    """
    input([prompt]) -> value
    
    Equivalent to eval(raw_input(prompt)).
    """
    pass


如果要输入字符串,需要手动加引号
a = raw_input()
print(a, type(a))

b = raw_input()
print(b, type(b))

# 控制台输出结果
123
(123, <type \'int\'>)
\'hello\'
(\'hello\', <type \'str\'>)


### raw_input raw_input与python3里面的input一样,输入的内容都会转化成字符串
a = raw_input()
print(a, type(a))

b = raw_input()
print(b, type(b))


控制台输出结果
123
(\'123\', <type \'str\'>)
hello
(\'hello\', <type \'str\'>)


## 小结 - python3只有input,输入的数据都会转化成字符串 - python2有input和raw_input,input读取原始的数据类型,输入什么就得到什么;raw_input获取到的都是字符串类型 补充:关于input的底层实现,参考博客 python中print和input的底层实现

分类:

技术点:

相关文章:

  • 2022-01-22
  • 2021-12-02
  • 2021-09-20
  • 2022-12-23
  • 2021-12-04
  • 2022-02-24
  • 2021-10-31
  • 2021-12-04
猜你喜欢
  • 2022-12-23
  • 2021-12-14
  • 2021-08-28
  • 2021-12-04
  • 2022-12-23
  • 2021-12-04
  • 2021-11-03
相关资源
相似解决方案