当前位置:首页>python>Python 语法第二课:输入与数据类型

Python 语法第二课:输入与数据类型

  • 2026-10-11 06:44:29
Python 语法第二课:输入与数据类型

点击蓝字

关注我们

01.input:让程序“听”你说话

input()函数负责接收用户的键盘输入。当程序运行到input()时,会暂停并等待用户输入内容,按下回车键后,输入的内容就会被保存起来。

name = input("请输入你的名字:")print("你好," + name + "!")

运行结果:

请输入你的名字:小明你好,小明!

核心避坑:input 的返回值永远是字符串

这是新手最容易踩的坑!无论你输入的是数字还是字母,input() 接收到的数据永远是字符串(str)类型。

age = input("请输入你的年龄:")print(age + 1)  # ❌ 报错!TypeError: can only concatenate str (not "int") to str
age = input("请输入你的年龄:")print(age + 1)  # ❌ 报错!TypeError: can only concatenate str (not "int") to str

02.三大基础数据类型

Python 是动态类型语言,但数据本身是有明确分类的。你可以用type() 函数随时查看变量的数据类型。三大基础数据类型如下:

a = 10        # 整数(int)b = 3.14      # 浮点数(float)c = "Hello"   # 字符串(str)print(type(a))  # <class 'int'>print(type(b))  # <class 'float'>print(type(c))  # <class 'str'>

类型转换:数据的“变身术”

既然input()返回的是字符串,我们在做数学计算前,就必须把它转换成数字类型:

age_str = input("请输入你的年龄:")  # 假设输入 18age_int = int(age_str)              # 将字符串转换为整数print("明年你就", age_int + 1, "岁啦!")

实际开发中,我们通常把input()和类型转换写在一起,代码更简洁:

age = int(input("请输入你的年龄:"))
print("苹果", "香蕉", "橙子", sep=" | ")# 输出结果:苹果 | 香蕉 | 橙子
print("苹果", "香蕉", "橙子", sep=" | ")# 输出结果:苹果 | 香蕉 | 橙子

03.实战:简易 BMI 计算器

让我们把input、type转换和print 结合起来,写一个真正有用的互动小程序!

print("=== 简易 BMI 计算器 ===")# 1. 获取用户输入并转换为浮点数height = float(input("请输入你的身高(米):"))weight = float(input("请输入你的体重(公斤):"))# 2. 计算 BMI 值bmi = weight / (height ** 2)# 3. 输出结果(保留两位小数)print(f"你的 BMI 指数为:{bmi:.2f}")

运行结果:

=== 简易 BMI 计算器 ===请输入你的身高(米):1.75请输入你的体重(公斤):70你的 BMI 指数为:22.86
name = "小明"      # 字符串类型age = 18           # 整数类型height = 1.75      # 浮点数类型print(name)        # 使用变量,输出:小明print(age, height) # 输出:18 1.75
name = "小明"      # 字符串类型age = 18           # 整数类型height = 1.75      # 浮点数类型print(name)        # 使用变量,输出:小明print(age, height) # 输出:18 1.75

最新文章

随机文章