# python之raw_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 'your age is %dn' % nAge
``````

#### 3.输入浮点型

``````fWeight = 0.0
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')
``````

``````# python guess.py
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

# python guess.py
yang
Traceback (most recent call last):
File "guess.py", line 10, in ?
myName = input()
File "<string>", line 0, in ?
NameError: name 'yang' is not defined

# python guess.py
"yang"
well, yang, i am thinking of a number between 1 and 23.
Take a guess
10
Take a guess
15
good job! you guess in 2 guesses!
``````

### 三、raw_input与input的区别

当输入为纯数字时

• input返回的是数值类型，如int,float
• raw_inpout返回的是字符串类型，string类型

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