python函数深入浅出|python函数深入浅出 2.input()函数详解

1.函数名及其来源 上一节说了输出,那么接下来就来说一下输入函数input()
input 源于英文,可做动词表示输入,也可作名词指输入设备,输入端
所以我们执行input示例:

s=input('Now your name is:') print(s)

程序执行的过程实际是
  • 计算机监听键盘输入的内容并放置于内存直到输入完成(按回车)
  • 读取你输入的内容并赋值给s
  • 通过print函数输出s到屏幕
2.函数定义源码及其用法拆解
input([prompt])

参数说明:
prompt: 提示信息,比如'请输入名字','请输入账号'等等
3.版本差异
Python3 中 input() 函数接受一个标准输入数据,返回为 string 类型。
Python2 中 input() 相等于 eval(raw_input(prompt)) ,用来获取控制台的输入。
raw_input() 将所有输入作为字符串看待,返回字符串类型。而input()在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float )。
例子:
python2中
>>>a = input("input int num:") input int:123# 输入整数 >>> type(a) # 整型>>> a = input("input float:") input float: 1.3# 正确,字符串表达式 >>> type(a) # 浮点数>>> a = input("input str:") input str:"string"# 正确,字符串表达式 >>> type(a) # 字符串>>> a = input("input:") input:string# 报错,不是表达式 Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'string' is not defined>>> a = raw_input("Please input your name: ") Please input your name: liming >>> a 'liming'# 字符串>>> a = raw_input("raw input num: ") raw input num: 1 >>> a '1'# 字符串

4.学习建议
善用input可以更方便的自定义输入参数,验证参数变化输出结果的变化。
使用python2的时候需要注意raw_input和input的区别。
python3中只保留了input,输入默认都是字符串,如需其他类型需自行转换。
某种程度上也减轻了入参校验的负担。
但如果期望输入的是非字符串类型,则一定不要忘记转换。
【python函数深入浅出|python函数深入浅出 2.input()函数详解】对基础运行环境有疑问的,推荐参考:python函数深入浅出 0.基础篇

    推荐阅读