python 筆記 raw_input()與input()的區別——12.24

習題 11:提問

開門見山,先敲點代碼

ex11.py

# -*- coding: utf-8-*-

print "How old are you?",

age =raw_input()

print "How tall are you?",

height = raw_input()

print "How much do you weigh?",

weight = raw_input()

 

print  "So you're %r old, %r tall and %rheavy."% (

age, height, weight)

 

 

運行結果:

 

 

 

 

感悟與自我測試:

在此簡單說下%r和%s的個人理解

%r是string轉義成repr,輸出對python比較友好

%s直接是str,它的輸出對於用戶比較友好

 

raw_input(),python的內建函數,通過讀取讀取控制檯的輸入實現用戶交互。

相似的內建函數還有input(),

raw_input直接讀取控制檯的輸出,支持任意類型的輸入。

Input()則希望能夠讀取一個合法的python表達式,必須使用引號括起來,儘量避免使用此函數

 

具體請看以下test

 

ex11_3.py

# -*- coding:utf-8-*-

print "what do you like?",

this =raw_input()

print"Oh,yes. I think %r is verygood!"%this

 

 

print "what do you like?",

that =input()

print"Oh,yes. I think %s is verygood!"%that

 

 

運行結果:

 

 

下面再簡單測下raw_input()與input()的區別

ex11_2.py    raw_input()

# -*- coding:utf-8-*-

print "How old are you?",

your_ages = raw_input()

print "How old are your brother?",

your_brother_ages = raw_input()

 

print"So ,your brother are older %r yearsthan you."%(your_brother_ages- your_ages)

 

運行結果:

 

 

 

 

 

ex11_2_2.py input()

# -*- coding:utf-8-*-

print "How old are you?",

your_ages = input()

print "How old are your brother?",

your_brother_ages = input()

 

print"So ,your brother are older %r yearsthan you."%(your_brother_ages- your_ages)

 

運行結果:

 

 

 

ex11_2_3.py  input()      ------實驗中輸出語法不對請忽視····

# -*- coding:utf-8-*-

print "How old are you?",

your_ages = input()

print "How old are your brother?",

your_brother_ages = input()

 

print"So ,your brother are older %r yearsthan you."%(your_brother_ages+ your_ages)

 

運行結果:

 

 

 

 

 x = int(raw_input())  個人理解爲簡單的嵌套函數

 

ex11_4.py

# -*- coding: utf-8-*-

 

 

print "How much money do you have?",

x =int(raw_input())

print "Oh, you have %r money."%x

 

 

運行結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章