python输入

  • 1.input 简介
  • 2.python2.x版本输入
  • 3.python3.x输入


1.input 简介

input是python基本的输入方式。
这次将带大家一起看一看不同版本的输入。

2.python2.x版本输入

python2.x输入与3.x不同,2.x中,字符串使用raw_input()来输入,input()来输入数字类型的东西。

a = input("数字:")
b = raw_input("任何字符:")
print(a)
print(b)

当输入不符合要求时,会报错,如:

>>> a = raw_input("任何字符:")
任何字符:hello
>>> a = input("数字:")
数字:12
>>> a = input("数字:")
数字:hello
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    a = input("数字:")
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

这里报错是因为输入时用的input(),它要么接受无引号的数,要么接受有引号的字符串,可是这里输入的字符串没有带引号,所以程序报错了。

3.python3.x输入

python3.x把raw_input()和input()合并成了input(),因为输入的东西默认是字符串,所以字符串不用加引号,但数字什么的都需要转换类型:

>>> a = input("你的名字:")
你的名字:Alex
>>> a = input("你的名字:") #再次输入,替换上一次的值
你的名字:121
>>> a
"121"
>>> a = int(a)
>>> a
121

可见,当没有转换类型时,即便输入的是数字121,存储的还是字符串,只有在int(a)后,a才变成了数字。