考纲考点
- 程序的基本语法元素:程序的格式框架、缩进、注释、变量、命名、保留字、数据类型、赋值语句、引用
- 基本输入输出函数:input()、eval()、print()
- 源程序的书写风格
知识导图
程序的格式框架
缩进
- python语言采用严格的“缩进”来表明程序的格式框架,表示包含和层次关系
- 1个缩进 = 4个空格 = tab键 两者不能混用
- 缩进是Python语言中表明程序框架的唯一手段
- 当表示分支、循环、函数、类等程序含义时,在 if、while、for、def、class 等保留字所在的完整语句后通过英文冒号(:)结尾并在之后进行缩进,表明后续代码与紧邻无缩进语句的所属关系
缩进直接影响运行结果
a=45
if a>45:
print("大于")
================= RESTART: D:/ing/python/python/files/eg2.py =================
# 不满足条件,所以不输出
a=46
if a>45:
print("大于")
================= RESTART: D:/ing/python/python/files/eg2.py =================
大于
a=46
if a>45:
print("100")
================= RESTART: D:/ing/python/python/files/eg2.py =================
100
a=42
if a>45:
print("大于")
print("100")
================= RESTART: D:/ing/python/python/files/eg2.py =================
100
a=42
if a>45:
print("大于")
print("100")
================= RESTART: D:/ing/python/python/files/eg2.py =================
注释
注释语句不参与程序运行,仅供程序阅读者参考阅读
a=70
if a>45:
print(">")
if a>60:
print("dd") #这是第二层
print("110")
================= RESTART: D:/ing/python/python/files/eg2.py =================
>
dd
110
多行注释
在Python中,使用三个单引号('''……''')或者三个双引号("""……""")作为多行注释的符号,一对三引号之前的代码都将被代码解释器忽略。
https://mp.weixin.qq.com/s?src=11×tamp=1580189279&ver=2123&signature=*Zv-xUFaI1ca6qsfWG57pos5Km1YhsnONFaUyw2XxJMkRD5ROzdnrwvCD69divgtzQhopKQgXgT9RUoYPczztHVmeYGZ1mbt0WAfuYNpK9NAzL2f5TgDTincZkoR8Cqw&new=1
>>>
'''
登录模块
开发者:Allen
版本号:1.0
时间:2019年10月
'''
'\n登录模块\n开发者:Allen\n版本号:1.0\n时间:2019年10月\n'
>>> """
注释内容1
注释内容2
"""
'\n注释内容1\n注释内容2\n'
续行符
print("{}是{}的首都".format(\
"北京",\
"中国"\
))
等价于
print("{}是{}的首都".format("北京","中国"))
语法元素的名称(重点)
变量
用来存储数据的空间(地址),是可变值
求和:sum
>>> s=456
>>> s
456
>>> s+1
457
>>> str="abcd"
>>> str
'abcd'
a=70
if a==70:
print("==")
================= RESTART: D:/ing/python/python/files/eg2.py =================
==
命名
python语言允许采用大写字母、小写字母、数字、下划线(_)和汉字等字符及其组合给变量命名,但名字的首字符不能为数字,中间不能出现空格,长度没有限制,保留字不能作为变量。
注意:标识符对大小写敏感,python和Python是两个不同的名字
>>> a5=45
>>> a5
45
>>> a-=78 #-=是Python里的一个运算符
#等同于a=a-78
#a-不能定义为一个变量
>>> a
-8
>>> a-
SyntaxError: invalid syntax
#错误,a-不组合,-=组合
>>> if=45
SyntaxError: invalid syntax
>>> if
SyntaxError: invalid syntax
#保留字不能被定义为变量
>>> a3
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
a3
NameError: name 'a3' is not defined
#没有被定义过
保留字
- “关键字”,被编程语言内部定义并保留的标识符
- 程序员编写程序不能定义与保留字相同的标识符
- 每种程序设计语言都有一套保留字,保留字一般用来构成程序整体框架,表达关键值和具有结构性的复杂语义等
- 掌握一门编程语言首先要熟记其所对应的保留字
python3.x保留字列表
序号 | 保留字 | 说明 |
---|---|---|
1 | and | 用于表达式运算,逻辑与操作 |
2 | as | 用于类型转换 |
3 | assert | 断言,用于判断变量或条件表达式的值是否为真 |
4 | async | |
5 | await | |
6 | break | 中断循环语句的执行 |
7 | class | 用于定义类 |
8 | continue | 继续执行下一次循环 |
9 | def | 用于定义函数或方法 |
10 | del | 删除变量或序列的值 |
11 | elif | 条件语句,与 if,else 结合使用 |
12 | else | 条件语句,与 if,elif结合使用,也可以用于异常和循环语句 |
13 | except | 包含捕获异常后的操作代码块,与 try,finally 结合使用 |
14 | False | |
15 | finally | 用于异常语句,与 try,except 结合使用 |
16 | for | for循环 |
17 | form | 用于导入模板,与 import 结合使用 |
18 | global | 定义全局变量 |
19 | if | 条件语句,与 else,elif 结合使用 |
20 | import | 多用于导入模板,与 form 结合使用 |
21 | in | 判断变量是否在序列中 |
22 | is | 判断变量是否为某个类的实例 |
23 | lambda | 定义匿名函数 |
24 | None | |
25 | nonlocal | |
26 | not | 用于表达式运算,逻辑非操作 |
27 | or | 用于表达式运算,逻辑或操作 |
28 | pass | 空的类,方法或函数的占位符 |
29 | raise | 异常抛出操作 |
30 | return | 用于函数返回计算结果 |
31 | Ture | |
32 | try | try包含可能出现异常的语句,与 except,finally 结合使用 |
33 | while | 循环语句 |
34 | with | 简化 python 的语句 |
35 | yield | 用于从函数依次返回值 |
数据类型
简单:数字类型,字符串类型
略微复杂:元组类型,集合类型,列表类型
数字类型
表示数字或数值的数据类型(整数、浮点数(实数)、复数)
整数值:
二进制:0b
八进制:0o
十进制:1010=1×103+0×102+1×10^1+0
十六进制:0x3F2=3×162+15×161+2
eg:0x17=16+7=23
10 | 11 | 12 | 13 | 14 | 15 |
---|---|---|---|---|---|
A | B | C | D | E | F |
>>> 0xf
15
>>> 0o1762
1010
>>> 0b10
2
一个浮点数可以表示为带有小数点的一般形式,也可以采用科学计数法表示
eg:浮点数123.456
一般形式:123.456
科学计数法:1.2345e2
复数:a+bj
字符串
双引号“ ”或单引号‘ ’
反向递减序号 ←
-11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
---|---|---|---|---|---|---|---|---|---|---|
H | e | l | l | o | W | o | r | l | d | |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
正向递减序号 →
>>> "a4558"[3]
'5'
>>> "a4558"[4]
'8'
>>> "中国人民"[-2]
'人'
>>> "中国人民"[1]
'国'
#左读0开始,右读-1开始
>>> a='中国人民解放军'
>>> a[2:4] #[2:4] 表示 ≥2,<4
'人民'
>>> a='中国人民解放军'
>>> a[1:-2]
'国人民解'
>>> a[-1:2]
'' #空集
a='456789'
if len(a)>5:
print("长度超出范围")
================= RESTART: D:/ing/python/python/files/eg3.py =================
长度超出范围
a='456789'
if len(a[-2:1])>5:
print("长度超出范围")
================= RESTART: D:/ing/python/python/files/eg3.py =================
注意:一个汉字或一个字母的长度都是1
>>> len("譬如朝露,去日苦多")
9
>>> len("譬如朝露,去日苦多。")
10
>>> len("Hello World")
11
>>> len("HelloWorld")
10
程序的语句元素
表达式
eg:3+2
由数据和操作符组成
>>> 45>=10
True
>>> 45!=10 #!=表示不等于
True
>>> 45==10
False
赋值语句
eg:a3+2
>>> a=45
>>> a,b=47,"ab"
>>> a,b
(47, 'ab')
>>> a+45
92
>>> b+1
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
b+1
TypeError: Can't convert 'int' object to str implicitly
>>> a,b=47,"ab"
>>> a,b=b,a
>>> a,b
('ab', 47)
引用
python开源→引用
>>> import turtle
>>> turtle.fd(-200) #fd:前进
>>> import turtle
>>> turtle.right(90)
>>> turtle.circle(200)
其他语句
分支语句
循环语句
作业
- 获得用户输入的一段文字,将这段文字进行垂直输出
s=input("请输入一段文本:")
i=-1*len(s)
while i <=-1:
print(s[i])
i=i+1
================= RESTART: D:/ing/python/python/files/2-1.py =================
请输入一段文本:Hello
H
e
l
l
o
>>>
================= RESTART: D:/ing/python/python/files/2-1.py =================
请输入一段文本:中华人民共和国
中
华
人
民
共
和
国
- 获得用户输入的一个实数,提取并输出其小数部分
a=eval(input("请输入实数:"))
b=int(a)
c=a-b
print("{}".format(round(c,4)))
================= RESTART: D:/ing/python/python/files/2-2.py =================
请输入实数:256.356
0.356
- 时针代码
(输入有误,待检查)
import turtle
from datetime import *
#抬起画笔,向前运动一段距离放下
def Skip(step):
turtle.penup()
turtle.forward(step)
turtle.pendown()
def mkHand(name,length):
#注册 Turtle 形状,建立表针 Turtle
turtle.reset()
Skip(-length*0.1)
#开始记录多边形的顶点,当前的乌龟位置是多边形的第一个顶点
turtle.begin_poly()
turtle.forword(length*1.1)
#停止记录多边形的顶点,当前的乌龟位置是多边形的最后一个顶点,将于第一个顶点相连
turtle.end_poly()
#返回最后记录的多边形
handForm = turtle.get_poly()
turtle.register_shape(name,handForm)
def Init():
global secHand,minHand,hurHand,printer
#重置Turtle指向北
turtle.model("logo")
#建立三个表针 Turtle 并初始化
mkHand(*secHand*.135)
mkHand(*minHand*.125)
mkHand(*hurHand*.90)
secHand = turtle.Turtle()
secHand.shape("secHand")
minHand = turtle.Turtle()
minHand.shape("minHand")
hurHand = turtle.Turtle()
hurHand.shape("hurHand")
for hand in secHand,minHand,hueHand:
hand.shapesize(1,1,3)
hand.speed(0)
#建立输出文字 Turtle
printer = turtle.Turtle()
#隐藏画笔的 turtle 形状
printer.hideturtle()
printer.penup()
def SetupClock(radius):
#建立表的外框
turtle.reset()
turtle.pensize(7)
for i in range(60):
Skip(radius)
if i%5==0:
turtle.forward(20)
Skip(-radius -20)
Skip(radius+20)
if i == 0:
turtle.write(int(12),align="center",font=("Courier",14,"bold"))
elif i == 30:
Skip(25)
turtle.write(int(i/5).align="center".font-("Courier",14,"bold"))
Skip(-25)
elif(i == 25 or i == 35):
Skip(20)
turtle.write(int(i/5), align="center", font=("Courier",14,"bold"))
Skip(-20)
else:
turtle.write(int(i/5), align="center", font=("Courier",14,"bold"))
Skip(-radius - 20)
else:
turtle.dot(5)
Skip(-radius)
turtle.right(6)
def Week(t):
week = ("星期一","星期二","星期三","星期四","星期五","星期六","星期日")
return week[t.weekday()]
def Date(t):
y = t.year
m = t.month
d = t.day
return "%s%d%d"%(y,m,d)
def Tick():
#绘制表针的动态显示
t = datetime.today()
second = t.second + t.microsecond*0.000001
minute = t.minute + second/60.0
hour = t.hour + minute/60.0
secHand.setheading(6*second)
minHand.setheading(6*minute)
minHand.setheading(30*hour)
turtle.tracer(False)
printer.forward(65)
printer.write(Week(t), align="center", font=("Courier",14,"bold"))
printer.back(130)
printer.write(Date(t), align="center", font=("Courier",14,"bold"))
priter.home()
turtle.tracer(True)
#100ms后继续调用tick
turtle.ontimer(Tick,100)
def main():
#打开/关闭龟动画,并为更新图纸设置延迟
turtle.tracer(False)
Init()
SetupClock(160)
turtle.tracer(True)
Tick()
turtle.mainloop()
if_name_=="_main_";
main()
②https://www.cnblogs.com/springcloud/p/8624040.html
# !/urs/bin/ python
# _*_ coding: utf-8
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import turtle
import datetime
# 移动一段距离
def skip(distance):
"""
移动乌龟一段距离,不留痕迹
:param distance: 像素
:return:
"""
turtle.penup()
turtle.forward(distance)
turtle.pendown()
def draw_clock():
# 先画表盘
# 先画点
# 移动一段距离,画一个点,然后退回
# 转动6°,再移动一段距离,画一个点,然后退回
# 循环 60次
# 让乌龟的方向默认向上
turtle.reset()
turtle.hideturtle()
for i in range(60):
skip(160)
# 根据 5格一个时钟
if i % 5 == 0:
turtle.pensize(7)
# 画时钟
turtle.forward(20)
if i == 0:
turtle.write(12, align='center', font=('Courier', 14, 'bold'))
elif i == 25 or i == 30 or i == 35:
skip(25)
turtle.write(int(i / 5), align='center', font=('Courier', 14, 'bold'))
skip(-25)
else:
turtle.write(int(i / 5), align='center', font=('Courier', 14, 'bold'))
skip(-20)
else:
turtle.pensize(1)
turtle.dot()
skip(-160)
turtle.right(6)
def get_week(t):
week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
return week[t.weekday()]
def create_hand(length, name):
turtle.reset()
skip(-length * 0.1)
turtle.begin_poly()
turtle.forward(length * 1.1)
turtle.end_poly()
# 注册
turtle.register_shape(name, turtle.get_poly())
hand = turtle.Turtle()
hand.shape(name)
hand.shapesize(1, 1, 3)
return hand
def run():
# 不停的获取时间
t = datetime.datetime.today()
bob.forward(65)
bob.write(get_week(t), align='center', font=('Courier', 14, 'bold'))
bob.back(130)
bob.write(t.strftime('%Y-%m-%d'), align='center', font=('Courier', 14, 'bold'))
bob.home()
# 指针移动
second = t.second + t.microsecond * 0.000001
minute = t.minute + second / 60
hour = t.hour + minute / 60
turtle.tracer(True)
second_hand.setheading(6 * second)
minute_hand.setheading(6 * minute)
hour_hand.setheading(30 * hour)
turtle.ontimer(run, 200)
if __name__ == '__main__':
# 画秒针,分针,时针
turtle.mode('logo')
turtle.hideturtle()
global second_hand, minute_hand, hour_hand, bob
second_hand = create_hand(135, 'second_hand')
minute_hand = create_hand(125, 'minute_hand')
hour_hand = create_hand(90, 'hour_hand')
# 创建一个新的turtle对象,去循环的操作
bob = turtle.Turtle()
bob.hideturtle()
bob.penup()
turtle.tracer(False)
draw_clock()
run()
turtle.mainloop()