Python input()函数:获取用户输入的字符串
input() 函数的用法为:
str = input(tipmsg)
说明:
- str 表示一个字符串类型的变量,input 会将读取到的字符串放入 str 中。
- tipmsg 表示提示信息,它会显示在控制台上,告诉用户应该输入什么样的内容;如果不写 tipmsg,就不会有任何提示信息。
【实例】input() 函数的简单使用:
a = input("Enter a number: ") b = input("Enter another number: ") print("aType: ", type(a)) print("bType: ", type(b)) result = a + b print("resultValue: ", result) print("resultType: ", type(result))
运行结果示例:
Enter a number: 100↙
Enter another number: 45↙
aType: <class 'str'>
bType: <class 'str'>
resultValue: 10045
resultType: <class 'str'>
↙
表示按下回车键,按下回车键后 input() 读取就结束了。
本例中我们输入了两个整数,希望计算出它们的和,但是事与愿违,Python 只是它们当成了字符串,+
起到了拼接字符串的作用,而不是求和的作用。
我们可以使用 Python 内置函数将字符串转换成想要的类型,比如:
- int(string) 将字符串转换成 int 类型;
- float(string) 将字符串转换成 float 类型;
- bool(string) 将字符串转换成 bool 类型。
修改上面的代码,将用户输入的内容转换成数字:
a = input("Enter a number: ") b = input("Enter another number: ") a = float(a) b = int(b) print("aType: ", type(a)) print("bType: ", type(b)) result = a + b print("resultValue: ", result) print("resultType: ", type(result))
运行结果:
Enter a number: 12.5↙
Enter another number: 64↙
aType: <class 'float'>
bType: <class 'int'>
resultValue: 76.5
resultType: <class 'float'>
关于 Python 2.x
上面讲解的是 Python 3.x 中 input() 的用法,但是在较老的 Python 2.x 中情况就不一样了。Python 2.x 共提供了两个输入函数,分别是 input() 和 raw_input():
- Python 2.x raw_input() 和 Python 3.x input() 效果是一样的,都只能以字符串的形式读取用户输入的内容。
- Python 2.x input() 看起来有点奇怪,它要求用户输入的内容必须符合 Python 的语法,稍有疏忽就会出错,通常来说只能是整数、小数、复数、字符串等。
比较强迫的是,Python 2.x input() 要求用户在输入字符串时必须使用引号包围,这有违 Python 简单易用的原则,所以 Python 3.x 取消了这种输入方式。
修改本节第一段代码,去掉 print 后面的括号:
a = input("Enter a number: ") b = input("Enter another number: ") print "aType: ", type(a) print "bType: ", type(b) result = a + b print "resultValue: ", result print "resultType: ", type(result)
在 Python 2.x 下运行该代码:
Enter a number: 45↙
Enter another number: 100↙
aType: <type 'int'>
bType: <type 'int'>
resultValue: 145
resultType: <type 'int'>
相关文章
- 【水水水文章】用 Python 发邮件
- 苹果电脑python官网下载步骤-Python下载和安装图文教程[超详细]
- python进制转换函数-Python中进制转换函数的使用
- python大数据分析实例-用Python整合的大数据分析实例
- Python入门系列(六)一篇学会python函数
- 简述python变量的命名规则_Python 变量命名规则
- python中替换字符串中字符_Python replace()函数:替换字符串中的某个字符「建议收藏」
- python判断linux中文件是否存在_Python判断文件是否存在的三种方法
- python不同开根号速度对比[通俗易懂]
- python 主函数 输入
- python常见运维脚本_Python运维常用脚本[通俗易懂]
- python+csv+datetime+pushplus的值班提醒推送2020.12.19
- 【说站】python整数的用法整理
- 【说站】python里的π怎么输入
- 【说站】python输入三个数字从小到大排序
- 【测试开发】python系列教程:第一个Python程序
- Python的特点是什么_python具有的特点
- python-Python与SQLite数据库-SQLite数据库的基本知识(二)
- Python是什么,Python简介
- Python学习:6.python内置函数详解编程语言
- Python学习:1.快速搭建python环境详解编程语言
- 使用Python执行Linux命令的方法(python调用linux命令)
- 使用Python操作MySQL数据库快速上手(python访问mysql数据库)
- 《Python官方文档》5.数据结构
- 使用Python连接SQL Server数据库(python连接sqlserver)
- python提取文件的小程序
- Python的内存泄漏及gc模块的使用分析
- python中类的一些方法分析