Files

68 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Day_2 · 变量与数据类型
> 预计耗时:20~30 分钟
> 今天学:怎么往"盒子"里装数据(变量),以及数据分哪几种类型。
## 今日知识点
- 变量:`名字 = 值` 就能存数据,比如 `name = "张三"`
- 常见类型:`int` 整数、`float` 小数、`str` 字符串(带引号)、`bool` 布尔(True/False)
- `type(变量)` 可以查看类型;`input("提示")` 可以让用户从键盘输入(输入的一定是字符串)
## 先学(教程)
- 菜鸟教程(看"数据类型"一节,基础语法那节也顺带扫一眼):https://www.runoob.com/python3/python3-data-type.html
- B站黑马教程(看讲"变量、数据类型、输入"的几集):https://www.bilibili.com/video/BV1qW4y1a7fU/
## 任务(后做)
1. 新建 `day2.py`,写以下代码并运行,**先猜输出,再对答案**:
```python
name = "张三"
age = 18
score = 88.5
is_student = True
print(name)
print(type(name), type(age), type(score), type(is_student))
```
2. 用 `input()` 写一个打招呼程序:
```python
your_name = input("请输入你的名字:")
print("你好," + your_name + "!")
```
运行后输入你的名字,确认能回应。
3. **进阶(加分)**:`input()` 输入的是字符串,试试
`age = input("几岁?")` 后运行 `print(age + 1)`,观察报错,再用 `int(age) + 1` 修复它。
## 完成标准
- [ ] 任务 1 的类型打印正确(str / int / float / bool)
- [ ] 任务 2 能正常打招呼
- [ ] (进阶)能把字符串转成 int 再运算
**提交方式**:把 `day2.py` 的代码贴在当日工单评论里。
## 参考解答(先做再看)
```python
name = "张三"
age = 18
score = 88.5
is_student = True
print(name) # 张三
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(score)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
your_name = input("请输入你的名字:")
print("你好," + your_name + "!")
# 进阶
age = input("几岁?") # 输入的是字符串 "18"
# print(age + 1) # 报错:字符串不能直接加整数
print(int(age) + 1) # 19:int() 把字符串转成整数
```