第 4 天|输入、类型转换与业务计算¶
日期: 2026 年 7 月 23 日
核心内容: input()、int()、float()、算术运算、f-string 和 .2f
科图题中的最小业务公式:
销售总价 = 销售数量 × 商城价格
input() 的返回值¶
quantity_text = input("请输入销售数量:")
input() 会:
- 显示提示文字;
- 等待键盘输入;
- 在按下回车后返回输入内容;
- 返回类型始终是
str。
输入 125 得到的是 "125",不能直接当作整数使用。
类型转换¶
| 原始文本 | 业务含义 | 转换代码 | 转换结果 |
|---|---|---|---|
"125" |
销售数量 | int("125") |
整数 125 |
"199.0" |
商城价格 | float("199.0") |
小数 199.0 |
"双肩包" |
商品名称 | 不转换 | 文本 |
int() 适合整数文本,float() 适合可能带小数点的文本。
转换前后对比¶
quantity_text = "125"
price_text = "199.0"
quantity = int(quantity_text)
price = float(price_text)
print(quantity_text, type(quantity_text))
print(quantity, type(quantity))
print(price_text, type(price_text))
print(price, type(price))
125 <class 'str'> 125 <class 'int'> 199.0 <class 'str'> 199.0 <class 'float'>
完整交互程序¶
product_name = input("请输入商品名称:")
quantity_text = input("请输入销售数量:")
price_text = input("请输入商城价格:")
quantity = int(quantity_text)
price = float(price_text)
total_sales = quantity * price
print(f"商品:{product_name}")
print(f"销售总价:{total_sales:.2f} 元")
代码解读¶
| 步骤 | 示例值 | 类型 |
|---|---|---|
| 输入品名 | "双肩包" |
str |
| 输入数量 | "125" |
str |
| 输入价格 | "199.0" |
str |
| 转换数量 | 125 |
int |
| 转换价格 | 199.0 |
float |
| 计算销售总价 | 24875.0 |
float |
| 格式化输出 | 24875.00 元 |
显示文本 |
先转换,再计算;不要把尚未转换的输入文本直接用于业务公式。
f-string 与小数格式¶
print(f"销售总价:{total_sales:.2f} 元")
| 部分 | 作用 |
|---|---|
f |
允许字符串中插入变量 |
{total_sales} |
读取变量值 |
:.2f |
显示两位小数 |
元 |
普通文本 |
.2f 只控制显示,不改变原始业务公式。这个区别会在青娅题“保留两位小数、不足补 0”中再次出现。
业务例题¶
| 商品 | 数量 | 价格 | 销售总价 |
|---|---|---|---|
| 双肩包 | 125 | 199.0 | 24875.00 |
| 帆布包 | 80 | 59.0 | 4720.00 |
| 拉杆箱 | 60 | 399.0 | 23940.00 |
手工计算一组结果,再用程序核对。真题中应先写清业务公式,再翻译成代码。