欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-02-16 10:44:51|栏目:Python代码|点击:

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

1、raw_input()

raw_input([prompt]) -> string

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

如:

print "Please input a num:"
k = raw_input()
print k
print type(k)

运行结果为:

Please input a num:
23
23
<type 'str'>

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

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

1)转为int型

print "Please input a num:"
n = int(raw_input())
print n
print type(n)

运行结果为:

Please input a num:
23
23
<type 'int'>

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

2)转为list型

print "please input list s:"
s = list(raw_input())
print s
print type(s)

运行结果为:

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

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

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

2、input()

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

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

如:

print "please input something :"
m = input()
print m
print type(m)

运行结果1为:

please input something :
23
23
<type 'int'>

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

运行结果2为:

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

print "please input something :"
m = str(input())
print m
print type(m)

运行结果为:

please input something :
23
23
<type 'str'>

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

2)转为int

print "please input something :"
m = int(input())
print m
print ty

运行结果为:

please input something :
23.5
23
<type 'int'>

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

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

上一篇:Python实现数值积分方式

栏    目:Python代码

下一篇:Windows10下Tensorflow2.0 安装及环境配置教程(图文)

本文标题:对python中raw_input()和input()的用法详解

本文地址:http://www.codeinn.net/misctech/64180.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有