python中str和input_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 "", 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”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值