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

一、raw_input

1.输入字符串

1nID = ''
2while 1:
3    nID = raw_input("Input your id plz")
4    if len(nID) != len("yang"):
5        print 'wring length of id,input again'
6    else:
7        break
8print 'your id is %s' % (nID)

2.输入整数

1nAge = int(raw_input("input your age plz:n"))
2if nAge > 0 and nAge < 120:
3    print 'thanks!'
4else:
5    print 'bad age'
6print 'your age is %dn' % nAge

3.输入浮点型

1fWeight = 0.0
2fWeight = float(raw_input("input your weightn"))
3print 'your weight is %f' % fWeight

4.输入16进制数据

1nHex = int(raw_input('input hex value(like 0x20):n'),16)
2print 'nHex = %x,nOct = %dn' %(nHex,nHex)

5.输入8进制数据

1nOct = int(raw_input('input oct value(like 020):n'),8)
2print 'nOct = %o,nDec = %dn' % (nOct,nOct)

raw_input,默认是返回的类型是字符串型,如果想要返回其他类型的数据时,需要在语句前加上相应的数据类型(如int 、float)。

二、input

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

1def input(prompt):
2    return (eval(raw_input(prompt)))

再看一个示例:

 1#!/usr/bin/python
 2# -*- coding: utf-8 -*-
 3# guess.py
 4import random
 5guessesTaken = 0
 6print ('Hello! what is your name')
 7#myName = raw_input()
 8myName = input()
 9number = random.randint(1, 23)
10print ('well, ' + myName + ', i am thinking of a number between 1 and 23.')
11while guessesTaken < 7:
12    print ('Take a guess')
13    guess = input()
14    #guess = int(guess)
15    guessesTaken = guessesTaken + 1
16    if guess < number:
17        print ('your guess is too low')
18    if guess > number:
19        print ('your guess is too high')
20    if guess == number:
21        break
22if guess == number:
23    print ('good job! you guess in %d guesses!' %guessesTaken)
24if guess != number:
25    print ('sorry! your guess is wrong')

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

 1# python guess.py
 2Hello! what is your name
 3111
 4Traceback (most recent call last):
 5  File "guess.py", line 12, in ?
 6    print ('well, ' + myName + ', i am thinking of a number between 1 and 23.')
 7TypeError: cannot concatenate 'str' and 'int' objects
 8使用不加引号的string
 9# python guess.py
10Hello! what is your name
11yang
12Traceback (most recent call last):
13  File "guess.py", line 10, in ?
14    myName = input()
15  File "<string>", line 0, in ?
16NameError: name 'yang' is not defined
17使用加引号的string
18# python guess.py
19Hello! what is your name
20"yang"
21well, yang, i am thinking of a number between 1 and 23.
22Take a guess
2310
24your guess is too low
25Take a guess
2615
27good 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”