常见数据结构
- 字符串 —— 用 双引号 或 单引号 括起来
- 数字
- 列表 —— 用 [ ] 括起来,逗号分隔
- 元组 —— 用()括起来,逗号分隔
- 字典 —— 用 { } 括起来, a:b为结构,逗号分隔
常用命令
1. 导入库 — import
import [库名]
2. 循环结构 — for,while
for 循环
for i in range( start , end ,step ):[循环内容]
while 循环
while [条件]:[循环内容]
3. 选择结构 — if, else
if [条件]:[满足时执行]else :[不满足时执行]
4. 定义方法 — def
def 方法名( 参数1, 参数2, ...):[方法内容]return [返回值]
- 终端输出 — print
print([输出内容])
常用库
- random 随机库
- turtle 乌龟库(画图)
- datetime 时间日期库
常见错误
1. 找不到变量
错误提示:NameError: name ‘xxx’ is not defined
(1) 将下面错误代码复制到thonny,并修改错误
a = random.randint(1,6)print(a)
(2)
birthday = input("请输入你的生日:格式为xxxx-xx-xx:")print(bithday)
该类错误改正方法:
- 如果是库,检查是否已经import
- 如果是变量,变量是否被定义
- 检查该名称是否拼错
2. 对齐不一致
错误提示:IndentationError: unindent does not match any outer indentation level
for i in rnage(1,10):pingfang = i * iprint(pingfang)
改正方法: 检查是否对齐
A1. 使用datetime库计算时间
运行示例代码
from datetime import datetimeprint(datetime.today())
听老师讲解
- 计算距离中考的天数
- 计算距离生日的天数
