类型与 input() · Python 从零开始
为什么 "3" + "4" 得到 34?怎样读取用户输入的内容?
课程目录为什么需要它
Python 里每个值都有类型 Type,类型决定了运算的含义:+ 对数字是相加,对字符串是拼接。和人交互的程序需要 input(),而 input() 返回的永远是文字,做数学之前必须先转换。类型搞混是初学者最常见的错误。
直觉理解
电话号码和数量看起来都是数字,但你绝不会把两个电话号码相加。Python 会记住每个值是哪一种东西:
| 类型 | 例子 | 含义 |
|---|---|---|
int 整数 | 42 | 整数 |
float 浮点数 | 3.5 | 小数 |
str 字符串 | "42" | 文字 |
bool 布尔值 | True | 是 / 否 |
类型转换 Type conversion:int("42") → 42,str(42) → "42",float("3.5") → 3.5。
input() 等用户输入一行,然后把它作为 str 返回。要当数字用就写:age = int(input())。
定义
数据类型 Data type
A data type is a category of values, such as int, float, str or bool, that determines which operations can be applied to them.数据类型是值的类别,比如 int、float、str、bool,它决定了这些值能做哪些运算。
input() 函数
input() reads one line typed by the user and returns it as a string.input() 读取用户输入的一行,并把它作为字符串返回。
在这个网站上,按「运行」之前先在「输入」框里写好要输入的内容。
示例
问问类型
动手试试type() 能告诉你任何值的类型。
print(type(3))
print(type(3.5))
print(type("3"))
print(type(True))逐步执行
- L1整数是 int。
<class 'int'> - L2有小数点就是 float。
<class 'float'> - L3在引号里就是 str,哪怕里面是数字。
<class 'str'> - L4True 和 False 是 bool。
<class 'bool'>
读取并转换
动手试试改一改「输入」框里的内容再运行。
name = input()
age = int(input())
print(name, "will be", age + 1, "next year")输入(每次 input() 读一行)
Ada 36
逐步执行
- L1读第一行输入,得到文字 "Ada"。
name = 'Ada' - L2读到 "36"(文字),int() 把它变成数字 36。
age = 36 - L3age 是数字,所以 age + 1 是 37。
Ada will be 37 next year
常见错误
input() 外面忘了加 int()
input() + 1 会报 TypeError:文字不能和数字相加。先转换:int(input()) + 1。
int() 只认整数
int("3.5") 和 int("seven") 都会报 ValueError。小数要用 float()。
小测验
1. 这段代码会输出什么?
print("5" * 3)查看答案
答案:B
字符串乘以数字,就是把字符串重复几遍。
2. 这段代码会输出什么?
print(int("7") + 3, "7" + "3")查看答案
答案:A
int("7") 是数字 7,7 + 3 = 10;"7" + "3" 是把两个字符串拼起来。
动手练习
3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。
- 预测输出文字还是数字?
准确写出程序的输出。
- 改需求真正地相加
这段程序读入两个数,却把它们拼在了一起(3 和 4 得到 34)。修改它,让它打印两数之和。
- 从零写分钟换算成小时
读入一个分钟数。第一行打印完整的小时数,第二行打印剩下的分钟数。输入 135 时输出 2 和 15。
本课术语
| 术语 | 中文 | 英文定义 |
|---|---|---|
| Data type | 数据类型 | A category of values that determines which operations apply to them. |
| int | 整数类型 | The type of whole numbers, such as 42. |
| float | 浮点数类型 | The type of numbers with a decimal point, such as 3.5. |
| input() | input() 输入函数 | A function that reads a line typed by the user and returns it as a string. |
| Type conversion | 类型转换 | Turning a value into another type, for example with int() or str(). |