Files
DailyChallenge_ProgrammingD…/Day_8/README.md
T
2026-08-22 01:09:30 +08:00

82 lines
2.1 KiB
Markdown
Raw 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_8 · 函数:把代码装进"盒子"反复用
> 预计耗时:20~30 分钟
> 后端每个页面就是一个函数(Django 的视图函数 `def index(request):`)。今天学定义和调用。
## 今日知识点
- 定义:`def 名字(参数):` ,用 `return` 返回结果
- 调用:`名字(实参)`
- 默认参数:`def greet(name="朋友"):` —— 不传就用默认值
- 函数的好处:写一次,到处调用;代码不重复
## 先学(教程)
- 菜鸟教程("函数"一节,重点看定义、参数、返回值):https://www.runoob.com/python3/python3-function.html
- B站黑马教程(看讲"函数"的几集):https://www.bilibili.com/video/BV1qW4y1a7fU/
## 任务(后做)
新建 `day8.py`:
1. 加法函数:
```python
def add(a, b):
return a + b
print(add(3, 5)) # 应该输出 8
print(add(10, 20)) # 30
```
2. 打招呼函数:
```python
def greet(name):
return f"你好,{name}!"
print(greet("张三"))
```
3. 默认参数:
```python
def greet2(name="朋友"):
return f"你好,{name}!"
print(greet2()) # 你好,朋友!
print(greet2("李四")) # 你好,李四!
```
4. **进阶(加分)**:写函数 `is_adult(age)`,年龄 ≥ 18 返回 `True` 否则 `False`,
然后用它给三个年龄(15、20、25)分别打印"成年/未成年"。
## 完成标准
- [ ] 任务 1~3 输出正确
- [ ] 能说出 `return` 和 `print` 的区别(函数里不 return 会返回什么?)
- [ ] (进阶)is_adult 结果正确
**提交方式**:把 `day8.py` 代码贴在当日工单评论里。
## 参考解答(先做再看)
```python
def add(a, b):
return a + b
print(add(3, 5)) # 8
def greet(name):
return f"你好,{name}!"
print(greet("张三"))
def greet2(name="朋友"):
return f"你好,{name}!"
print(greet2()) # 你好,朋友!
print(greet2("李四")) # 你好,李四!
# 进阶
def is_adult(age):
return age >= 18
for age in (15, 20, 25):
print(f"{age}岁:" + ("成年" if is_adult(age) else "未成年"))
```