程序或多或少都需要與用戶進(jìn)行交互,交互時(shí)一般按“提示-輸入-處理-輸出”流程走茎截。
今天學(xué)習(xí)python中用于接收用戶輸入的一個(gè)built-in-function(內(nèi)建函數(shù)):raw_input()
一衔憨、代碼
#E:\lszyy\python\examples\test.py
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 %r heavy." % (age, height, weight)
程序在打印完“How old are you?”后泣洞,緊跟著(逗號(hào)的作用)一根短橫線閃爍森书,等待用戶輸入
此時(shí)可根據(jù)提示輸入年齡使兔,而后輸入高度和體重建钥,輸出如下:
上述代碼還有另一種寫法:
#E:\lszyy\python\examples\test2.py
age = raw_input("How old are you?")
height = raw_input("How tall are you?")
weight = raw_input("How much do you weigh?")
print "So, you 're %r old, %r tall and %r heavy." % (age, height, weight)
很顯然這種寫法更加簡(jiǎn)潔。
仔細(xì)觀察輸出結(jié)果虐沥,輸入的數(shù)字熊经,輸出了字符串泽艘。
二、raw_input()
查看python幫助镐依,可以使用命令行查看匹涮,也可以查看python文檔
在命令行下輸入命令:
python -m pydoc raw_input
幫助信息如下:
E:\lszyy\python\examples>python -m pydoc raw_input
Help on built-in function raw_input in module __builtin__:
(__builtin__模塊中的內(nèi)建函數(shù)raw_input的幫助信息:)
raw_input(...)
raw_input([prompt]) -> string?(返回值為string類型)
Read a string from standard input.? The trailing newline is stripped.
(從標(biāo)準(zhǔn)輸入設(shè)備讀取一個(gè)字符串。去掉換行符槐壳。)
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
(如果用戶按下EOF符(Unix: Ctrl-D, Windows: Ctrl-Z+回車)然低,觸發(fā)EOF異常EOFError.)
On Unix, GNU readline is used if enabled.? The prompt string, if given,is printed without a trailing newline before reading.
(Unix系統(tǒng)中,如果啟用了的話宏粤,將使用GNU readline(一個(gè)開源的跨平臺(tái)程序庫脚翘,提供了交互式的文本編輯功能)灼卢。如果提供了提示字符串參數(shù)(prompt)绍哎,它將在讀取之前被輸出在屏幕上。)
三鞋真、其他獲取用戶命令行輸入的函數(shù)
input()
在命令行使用幫助:
python -m pydoc input
幫助信息如下:
E:\lszyy\python\examples>python -m pydoc input
Help on built-in function input in module __builtin__:
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
(等于eval(raw_input(prompt)))
對(duì)代碼稍作修改崇堰,將raw_input函數(shù)修改為input函數(shù):
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?")
print "So, you 're %r old, %r tall and %r heavy." % (age, height, weight)
在讀取輸入時(shí),input函數(shù)將根據(jù)用戶的輸入進(jìn)行類型轉(zhuǎn)換涩咖,輸入數(shù)字轉(zhuǎn)換成數(shù)字類型海诲,輸入字符串轉(zhuǎn)換成字符串類型,輸入字符串時(shí)需加引號(hào)檩互。
如1:
E:\lszyy\python\examples>python test2.py
How old are you?12
How tall are you?11
How much do you weigh?11
So, you 're 12 old, 11 tall and 11 heavy.
如2:
E:\lszyy\python\examples>python test2.py
How old are you?"sf"
How tall are you?"e"
How much do you weigh?"d"
So, you 're 'sf' old, 'e' tall and 'd' heavy.