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

yipeiwu_com6年前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代码编写的5个优化技巧

如今我使用 Python 已经很长时间了,但当我回顾之前写的一些代码时,有时候会感到很沮丧。例如,最早使用 Python 时,我写了一个名为 Sudoku 的游戏(GitHub地址:ht...

Python中的random.uniform()函数教程与实例解析

random.uniform( ) 函数教程与实例解析 1. uniform( ) 函数说明 random.uniform(x, y)方法将随机生成一个实数,它在 [x,y] ...

Python中的正则表达式与JSON数据交换格式

Python中的正则表达式与JSON数据交换格式

一、初识正则表达式 正则表达式 是一个特殊的字符序列,一个字符串是否与我们所设定的这样的字符序列,相匹配快速检索文本、实现替换文本的操作 json(xml) 轻量级 web 数据交换格式...

Python3 实现串口两进程同时读写

通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出 import threading,time import serial import str...

windows下安装python的C扩展编译环境(解决Unable to find vcvarsall.bat)

windows下安装python的C扩展编译环境(解决Unable to find vcvarsall.bat)

N久没有开始写博客了,总觉得要随便记点东西,岁月蹉跎,曾经搞得一些东西、技术、工具,说丢也就丢了,点点滴滴还是要记录一下吧。。。    在windows下使用pip安装一些python的...