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

yipeiwu_com7年前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中raw_input()和input()的用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python mac下安装虚拟环境的图文教程

python mac下安装虚拟环境的图文教程

Mac 下 Flask 框架 workon命令找不到 ---- 最终解决方案(详解具体实现操作过程中遇到的坑)2018年08月17日 00:02:05Jasonmes阅读数:622 Ma...

python logging添加filter教程

例子一 def filter(self, record): """Our custom record filtering logic. Built-in filter...

Python中用Descriptor实现类级属性(Property)详解

上篇文章简单介绍了python中描述器(Descriptor)的概念和使用,有心的同学估计已经Get√了该技能。本篇文章通过一个Descriptor的使用场景再次给出一个案例,让不了解情...

用Python制作检测Linux运行信息的工具的教程

在这篇文章里,我们将会探索如何使用Python语言作为一个工具来检测Linux系统各种运行信息。让我们一起来学习吧。 哪种Python? 当我提到Python时,我一般是指CPython...

解决pycharm安装后代码区不能编辑的问题

解决pycharm安装后代码区不能编辑的问题

此问题是由于最新的pycharm在安装时自动装了vimVim插件 你可以在tools Vim emulator将对勾去掉就可以了。 以上这篇解决pycharm安装后代码区不能编辑的问题...