程序或多或少都需要与用户进行交互,交互时一般按“提示-输入-处理-输出”流程走。
今天学习python中用于接收用户输入的一个built-in-function(内建函数):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?”后,紧跟着(逗号的作用)一根短横线闪烁,等待用户输入
此时可根据提示输入年龄,而后输入高度和体重,输出如下:
上述代码还有另一种写法:
#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)
很显然这种写法更加简洁。
仔细观察输出结果,输入的数字,输出了字符串。
二、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__模块中的内建函数raw_input的帮助信息:)
raw_input(...)
raw_input([prompt]) -> string (返回值为string类型)
Read a string from standard input. The trailing newline is stripped.
(从标准输入设备读取一个字符串。去掉换行符。)
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
(如果用户按下EOF符(Unix: Ctrl-D, Windows: Ctrl-Z+回车),触发EOF异常EOFError.)
On Unix, GNU readline is used if enabled. The prompt string, if given,is printed without a trailing newline before reading.
(Unix系统中,如果启用了的话,将使用GNU readline(一个开源的跨平台程序库,提供了交互式的文本编辑功能)。如果提供了提示字符串参数(prompt),它将在读取之前被输出在屏幕上。)
三、其他获取用户命令行输入的函数
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)))
对代码稍作修改,将raw_input函数修改为input函数:
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)
在读取输入时,input函数将根据用户的输入进行类型转换,输入数字转换成数字类型,输入字符串转换成字符串类型,输入字符串时需加引号。
如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.
2024 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123