脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 对python中raw_input()和input()的用法详解

对python中raw_input()和input()的用法详解

2021-02-04 00:27jv_rookie Python

下面小编就为大家分享一篇对python中raw_input()和input()的用法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

最近用到raw_input()和input()来实现即时输入,就顺便找了些资料来看,加上自己所用到的一些内容,整理如下:

1、raw_input()

?
1
raw_input([prompt]) -> string

系统介绍中是:读取标准输入的字符串。因此,无论输入的是数字或者字符或者其他,均被视为字符格式。

如:

?
1
2
3
4
print "Please input a num:"
k = raw_input()
print k
print type(k)

运行结果为:

?
1
2
3
4
Please input a num:
23
23
<type 'str'>

输入数字:23,输出:23,类型为str;

因此,在不同的场景下就要求输入的内容进行转换。

1)转为int型

?
1
2
3
4
print "Please input a num:"
n = int(raw_input())
print n
print type(n)

运行结果为:

?
1
2
3
4
Please input a num:
23
23
<type 'int'>

输入:23,输出:23,类型为int;

2)转为list型

?
1
2
3
4
print "please input list s:"
s = list(raw_input())
print s
print type(s)

运行结果为:

?
1
2
3
4
please input list s:
23
['2', '3']
<type 'list'>

输入:23,输出:[ '2','3' ],类型为list;

如何直接生成数值型的list尚未解决,算个思考题吧。

2、input()

?
1
2
input([prompt]) -> value
Equivalent to eval(raw_input(prompt))

可以看出,input()的输出结果是“值”,相当于是对raw_input()进行一个计算后的结果。

如:

?
1
2
3
4
print "please input something :"
m = input()
print m
print type(m)

运行结果1为:

?
1
2
3
4
please input something :
23
23
<type 'int'>

输入:23,输出:23,类型为int;

运行结果2为:

?
1
2
3
4
5
6
7
please input something :
abc
Traceback (most recent call last):
 File "D:/python test/ceshi1.py", line 24, in <module>
 m = str(input())
 File "<string>", line 1, in <module>
NameError: name 'abc' is not defined

输入:abc,输出报错(字符型的输入不通过);

但也可以把input()的结果进行转换:

1)转为str

?
1
2
3
4
print "please input something :"
m = str(input())
print m
print type(m)

运行结果为:

?
1
2
3
4
please input something :
23
23
<type 'str'>

输入为数值型的23,输出:23,类型为str;

2)转为int

?
1
2
3
4
print "please input something :"
m = int(input())
print m
print ty

运行结果为:

?
1
2
3
4
please input something :
23.5
23
<type 'int'>

输入:23.5,输出:23,类型为int(默认为向下取整);

注:input()不可使用list转为列表。

以上这篇对python中raw_input()和input()的用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/jv_rookie/article/details/55101196

延伸 · 阅读

精彩推荐