python的输入
文章目录
1.python版本python3.x
- input():接收任意数据类型
注意:python3.x中没有raw_input()
>>> input('Num:')
Num:2
'2'
>>> input('Num:')
Num:redhat
'redhat'
>>> input('Num:')
Num:1.2
'1.2'
>>> input('Num:')
Num:False
'False'
- 输入内容不回显
>>> import getpass ##设定输入密码不回显
>>> num = getpass.getpass('请输入密码:')
请输入密码:
>>> num
'123'
2.python版本python2.x
input():只支持正确的数值类型;raw_input():数值和字符串
>>> input('Num:')
Num:2
2
>>> input('Num:')
Num:1.2
1.2
>>> input('Num:')
Num:redhat
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'redhat' is not defined
>>> raw_input('Num:')
Num:2
'2'
>>> raw_input('Num:')
Num:1,2
'1,2'
>>> raw_input('Num:')
Num:redhat
'redhat'
>>>
3. 如果接收到的数值要进行比较的时候,一定要转换为同一种类型
>>> age = input('age:')
age:19
>>> age
'19'
>>> age > 18
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'
>>> age = int(input('age:'))
age:19
>>> age
19
>>> age > 18
True