python:第二十一章:input接收输入

发布时间 2023-11-19 09:44:30作者: 刘宏缔的架构森林

一,input函数的用途

input()函数用来从键盘接收用户的输入,
它的参数是提示用户输入的信息,
我们把接收到的数据保存到变量中,进行后续的操作

例子:

1
2
3
4
5
6
numPhysics = input("请输入物理成绩:")
numChemical = input("请输入化学成绩:")
# 接收的数字转为float类型然后相加
result = float(numPhysics) + float(numChemical)
 
print("理化的成绩为:" + str(result))

运行结果:

请输入物理成绩:88
请输入化学成绩:77
理化的成绩为:165.0

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/15/python-shi-yong-input-jie-shou-shu-ru/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,input函数默认接收到的变量类型是str

使用时要注意判断输入数据是否是需要类型,再从str转换

例子: isdigit方法用来判断变量是否数字

1
2
3
4
5
6
7
8
age = input("请输入您的年龄:")
print("输入值的类型:", type(age))
if age.isdigit():
    print("输入年龄是整数")
    ageInt = int(age)
    print("ageInt:值:", ageInt, ",类型:", type(ageInt))
else:
    print("输入年龄不是整数")

运行结果:

请输入您的年龄:35
输入值的类型: <class 'str'>
输入年龄是整数
ageInt:值: 35 ,类型: <class 'int'>