最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
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) |
二、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 " 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) |
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 |
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24