python之raw_input和input

在使用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 "<string>", 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”

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注