python input()和raw_input()

elvalad posted @ Jul 08, 2011 03:09:42 PM in Default , 7561 阅读

在python中input()和raw_input()函数均可以从终端输入,但二者存在一定区别,例如如下代码:

#!/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行中使用了input()函数,此时如果终端直接输入xxx,则会显示NameError: name 'xxx' is not defined的错误,如果输入"xxx"或'xxx'则可正确运行。

如果使用raw_input()函数,可直接输入xxx。

这两个函数的区别为如果直接键入数字,input()返回一个数值类型,比如int,float,而raw_input()则会返回字符串类型;如果键入非数字,则input()函数要求以字符串引用的形式输入,比如"xxx",而raw_input()可以直接输入为xxx,二者均返回字符串。

这里是input()和raw_input()内置函数的文档
Avatar_small
Mike Ma 说:
Jul 23, 2011 02:44:14 PM

简单解释:input是raw_input的壳子,会分析这个类型。
兼容性:input在py3.x中使用,raw_input在py.2.x中使用,不可互换


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter