一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python中raw_input和input用法与区别

时间:2014-06-11 编辑:简简单单 来源:一聚教程网

在使用python编写交互式程序时,经常用到的两个内部函数是raw_input和input(最常用还是input) ,本篇就通过一些示例看下两者之间的区别 。

一、raw_input
1.输入字符串

 代码如下 复制代码
nID = ''
while 1:
    nID = raw_input("Input your id plz")
    if len(nID) != len("yang"):
        print 'wring length of id,input again'
    else:
        break
print 'your id is %s' % (nID)

2.输入整数

 代码如下 复制代码
nAge = int(raw_input("input your age plz:n"))
if nAge > 0 and nAge < 120:
    print 'thanks!'
else:
    print 'bad age'
print 'your age is %dn' % nAge

3.输入浮点型

 代码如下 复制代码
fWeight = 0.0
fWeight = float(raw_input("input your weightn"))
print 'your weight is %f' % fWeight

4.输入16进制数据

 代码如下 复制代码
nHex = int(raw_input('input hex value(like 0x20):n'),16)
print 'nHex = %x,nOct = %dn' %(nHex,nHex)

5.输入8进制数据

 代码如下 复制代码

nOct = int(raw_input('input oct value(like 020):n'),8)
print 'nOct = %o,nDec = %dn' % (nOct,nOct)
raw_input,默认是返回的类型是字符串型,如果想要返回其他类型的数据时,需要在语句前加上相应的数据类型(如int 、float)。

二、input

input其实是通过raw_input来实现的,具体可以看python input的文档,原理很简单,就下面一行代码:

 代码如下 复制代码
def input(prompt):
    return (eval(raw_input(prompt)))

再看一个示例:

 代码如下 复制代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
# guess.py
import random
guessesTaken = 0
print ('Hello! what is your name')
#myName = raw_input()
myName = input()
number = random.randint(1, 23)
print ('well, ' + myName + ', i am thinking of a number between 1 and 23.')
while guessesTaken < 7:
    print ('Take a guess')
    guess = input()
    #guess = int(guess)
    guessesTaken = guessesTaken + 1
    if guess < number:
        print ('your guess is too low')
    if guess > number:
        print ('your guess is too high')
    if guess == number:
        break
if guess == number:
    print ('good job! you guess in %d guesses!' %guessesTaken)
if guess != number:
    print ('sorry! your guess is wrong')

上面的程序在执行时,无论使用数字或字符串,执行第10行的数据输入时,如果不加引号时会报错。执行过程如下:

使用int数字型

 代码如下 复制代码
# python guess.py
Hello! what is your name
111
Traceback (most recent call last):
  File "guess.py", line 12, in ?
    print ('well, ' + myName + ', i am thinking of a number between 1 and 23.')
TypeError: cannot concatenate 'str' and 'int' objects
使用不加引号的string
# python guess.py
Hello! what is your name
yang
Traceback (most recent call last):
  File "guess.py", line 10, in ?
    myName = input()
  File "", line 0, in ?
NameError: name 'yang' is not defined
使用加引号的string
# python guess.py
Hello! what is your name
"yang"
well, yang, i am thinking of a number between 1 and 23.
Take a guess
10
your guess is too low
Take a guess
15
good job! you guess in 2 guesses!

三、raw_input与input的区别

当输入为纯数字时

input返回的是数值类型,如int,float
raw_inpout返回的是字符串类型,string类型
当输入字符串时, input会计算在字符串中的数字表达式,而raw_input不会。

如输入 “57 + 3”:

input会得到整数60
raw_input会得到字符串”57 + 3”

在版本2和版本3中的区别

 代码如下 复制代码

Python 2.3.4 (#1, Feb  2 2005, 11:44:13)
[GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> user=raw_input("please input:")      
please input:wei                          #  raw_input 输入  字符串  成功
>>> user
'wei'
>>> user=input("please input:")         
please input:123                          #  input 输入  数字  成功(返回的是数字)
>>> user
123
>>> user=raw_input("please input:")
please input:111      #  raw_input 输入  数字  成功(返回的还是当成字符串)
>>> user
'111'
>>> user=input("please input:")
please input:wei                          #  input  输入字符串   失败
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 0, in ?
NameError: name 'wei' is not defined

ython 2.7.3 同上

在Python 3.2.3中  input和raw_input 整合了,没有了raw_input

 代码如下 复制代码

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> user=raw_input("please input:")                 #没有了raw_input
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'raw_input' is not defined
>>> user=input("please input:")
please input:wei
>>> user
'wei'
>>> user=input("please input:")                     #input的输出结果都是作为字符串
please input:123
>>> user
'123'

热门栏目