1、变量、表达式与语句:
1.1 掌握变量命名规则、熟悉Python保留关键字
标识符是由字符(A~Z 和 a~z)、下划线和数字组成,但第一个字符不能是数字。
标识符不能和 Python 中的保留字相同。
Python中的标识符中,不能包含空格、@、% 以及 $ 等特殊字符
1.1.1掌握语句概念以及Python语句特征
1.1.2掌握表达式合法性概念
1.2 掌握运算符、模运算以及运算顺序的规则 / % // ** *
a = 100
b = 101
a, b = b, a
print(a, b)
print(10 // 3)
print(10 / 3)
print(2 ** 4)
print(2*4)
答案:
101 100
3
3.3333333333333335
16
8
1.3 掌握输入的基本方式
# input输入
name = input("请输入你的名字:")
age = int(input("请输入你的年龄:"))
print(type(name), type(age))
1.4 掌握注释的书写方法 #
2、字符串
2.1掌握字符串是字符序列这一概念
2.1.1掌握len函数
print('string length =', len('abc'))
print('tuple length =', len((1, 2, 3))) # tuple
print('list length =', len([1, 2, 3, 4])) # list
print('bytes length =', len(bytes('abc', 'utf-8'))) # bytes
print('range length =', len(range(10, 20, 2))) # range
string length = 3 tuple length = 3
list length = 4 bytes length = 3
range length = 5 range(10, 20, 2)
2.2掌握通过循环遍历字符串的方法
例题1:构造一个3*4的矩阵,实现该矩阵的转置
shuzu = [[1, 2, 2, 3], [3, 4, 4, 5], [5, 6, 7, 8]]
xin = []
for i in range(4):
temp = []
for n in range(3):
temp.append(shuzu[n][i])
xin.append(temp)
print(xin)
例题2:有一组商品价格列表,利用列表生成式生成一个打95折的价格列表。
prices = [100, 200, 3000, 4000, 450, 100, 200, 400]
discount_price = [price * 0.9 for price in prices]
print(discount_price)
2.3掌握字符串分割的方法(切片法;split;replace)
用split分割字符串
# 1.根据空格分割字符串
apple = "a p p l e"
print(apple.split())
# 2.分割+最大分割:仅按前2个空格分割
print(apple.split(" ", 2))
str0 = 'a,b,c,d'
strlist = str0.split(',')# 用逗号分割str字符串,并保存到列表
print(strlist)
for value in strlist:# 循环输出列表值
print(value)
切片法
str = [1, 2, 3, 4, 6]
print(str[0:4])
# 输出str位置0开始到位置4以前的字符
replace方法
str1 = 'akakak'
str1 = str1.replace('k', ' 8')
# 将字符串里的k全部替换为 8
print(str1)
2.4掌握字符串是对象的概念
2.5掌握in运算符的应用
2.6掌握字符串比较方法(True False)
2.72.8熟悉字符串对象各种内置方法
a=list(map(int, input().split()))
a.remove(1)
print(a)
输入:1 2 3 4 5
输出:
2
3
4
5
2.8熟悉字符串解析方法和格式操作符
3、条件执行
3.1掌握布尔表达式概念
3.2掌握三种逻辑运算符的意义和用法
3.3掌握条件执行语句、分支执行和链式条件语句的写法
3.4掌握嵌套条件语句的写法
例题1: 输入一个学生成绩列表,把对应的等级列表打印出来
a = list(map(int, input().split()))
dengji = []
for number in a:
if 0 <= number <= 59:
dengji.append("E")
elif 60 < number <= 69:
dengji.append("D")
elif 70 < number <= 79:
dengji.append("C")
elif 80 < number <= 89:
dengji.append("B")
elif 90 < number <= 100:
dengji.append("A")
print(dengji)
例题2:掌握try与catch异常捕获概念与用法
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
except:
print('unknown error!')
else:
print("result is", result)
finally:
print("executing finally clause")
4、迭代
4.1掌握while语句迭代结构的用法和常见问题方式
4.1.1掌握break和continue的用法与区别
例题:编写程序,随机产生骰子的一面(1-6),给用户三次猜测机会,程序给出猜测提示(偏大或偏小),如果某次猜测正确,则提示正确并中断循环,如果三次均猜测错,则提示机会用完。
import random
i=(random.randint(1,6))
print(i)
for num in range(3):
a=eval(input("input:"))
if a>i:
print('偏大')
elif a<i:
print('偏小')
elif a==i:
print('刚刚好')
break;
if num==2:
print('机会已用完')
4.2掌握for循环结构的用法
4.2.1掌握统计求和、求最大最小值循环的程序实现方法
例题1: 计算两个矩阵的积
s = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
h = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
hhh = []
for i in range(3):
sss = []
for m in range(3):
sumk = 0
for k in range(3):
sumk += s[i][k] * s[m][k]
sss.append(sumk)
hhh.append(sss)
print(hhh)
5、列表 :[ ]
5.1掌握列表基本概念和可变特性
5.2掌握列表的遍历方法(for循环)
5.3掌握列表的运算符操作(*;+)、分割操作以及其他操作方法
shk=[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
print(shk*2)
print(shk+shk)
输出结果:[[1, 1, 1], [2, 2, 2], [3, 3, 3], [1, 1, 1], [2, 2, 2], [3, 3, 3]]
[[1, 1, 1], [2, 2, 2], [3, 3, 3], [1, 1, 1], [2, 2, 2], [3, 3, 3]]
5.4掌握列表中增加,删除元素的方法(insert;append;del; pop;clear;remove)
mydreamhoouse = ['bighouse', 'dog', 'pool', 'sofa']
print(mydreamhoouse)
# 列表增加元素append
mydreamhoouse.append('men')
print(mydreamhoouse)
# 列表插入元素insert
mydreamhoouse.insert(2, 'cat')
print(mydreamhoouse)
# 列表删除元素的三种方式:del pop remove
del mydreamhoouse[5]
print(mydreamhoouse)
a = mydreamhoouse.pop(0)
print(mydreamhoouse)
mydreamhoouse.remove('dog')
print(mydreamhoouse)
mydreamhoouse.reverse()
print(mydreamhoouse)
mydreamhoouse.sort()
print(mydreamhoouse)
print(len(mydreamhoouse))
mydreamhoouse.append('cake')
for a in mydreamhoouse:
print(a)
for a in mydreamhoouse:
print(mydreamhoouse)
输出结果为:
['bighouse', 'dog', 'pool', 'sofa']
['bighouse', 'dog', 'pool', 'sofa', 'men']
['bighouse', 'dog', 'cat', 'pool', 'sofa', 'men']
['bighouse', 'dog', 'cat', 'pool', 'sofa']
['dog', 'cat', 'pool', 'sofa']
['cat', 'pool', 'sofa']
['sofa', 'pool', 'cat']
['cat', 'pool', 'sofa']
3
cat
pool
sofa
cake
['cat', 'pool', 'sofa', 'cake']
['cat', 'pool', 'sofa', 'cake']
['cat', 'pool', 'sofa', 'cake']
['cat', 'pool', 'sofa', 'cake']
5.5掌握一些能用于列表的内嵌函数(len、max、min、sum等)
掌握列表与字符串之间的转换方式
1.列表转换为字符串
2. 字符串转换为列表
split str_0 = 'abcd'
result_0 = list(str_0)
result_1 = str_0.split()
print(result_0, result_1)
熟悉行间解析
掌握列表对象的复制方法
# 复制列表
lll = [1, 2, 3, 4]
mmm = lll[:]
print(mmm)
掌握列表的别名引用和列表参数
熟悉列表常见错误与调试方法
6、字典 : { key:value}
掌握字典概念及其与列表的区别
熟悉字典做计数器的使用方法
熟悉字典与文件的操作方法
掌握字典的循环方法
#字典的循环
zidian = {'book1': 'amy',
'book2': 'tony',
'book3': 'jerry'
}
for k,v in zidian.items():
print(f"\nKey: {k}")
print(f"Value:{v}")
输出结果:
Key: book1
Value:amy
Key: book2
Value:tony
Key: book3
Value:jerry
d = {'tom': 98, 'jerry': 90, 'jack': 50, 'rose': 60, 'lily': 88}
print(d.get('Jack', 1))
# 列表套字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'blue', 'points': 6}
alien_2 = {'color': 'red', 'points': 9}
aliens = [alien_2, alien_1, alien_0]
for alien in aliens:
print(alien)
# 字典套列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
print(f"you ordered a {pizza['crust']}-curst pizza")
# 访问配料列表
for topping in pizza['toppings']:
print("\t"+topping)
print("********************")
# 创建一个用于储存外星人的列表
aliens_1 = []
for alien_number in range(30):
new_alien = {'color': 'green', 'point': 6, 'speed': 9}
aliens_1.append(new_alien)
for alien in aliens_1[0:5]:
print(alien)
print("...")
print(f"Total number of aliens: {len(aliens_1)}")
输出结果:
1
{'color': 'red', 'points': 9}
{'color': 'blue', 'points': 6}
{'color': 'green', 'points': 5}
you ordered a thick-curst pizza
mushrooms
extra cheese
********************
{'color': 'green', 'point': 6, 'speed': 9}
{'color': 'green', 'point': 6, 'speed': 9}
{'color': 'green', 'point': 6, 'speed': 9}
{'color': 'green', 'point': 6, 'speed': 9}
{'color': 'green', 'point': 6, 'speed': 9}
...
Total number of aliens: 30
7、集合set:{,,}
掌握集合特点与列表的区别
集合无重复元素
8、元组 : ( )
元组基本特性及其与列表的区别:列表可以修改,但元组里的元素不行
若要修改只能重新定义整个元组
掌握元组sort函数
掌握元组赋值方法
熟悉元组与字典的区别
熟悉通过字典对元组进行多个赋值的方法
熟悉用元组进行高频词汇分析的方法并能应用到其它环境下
9、函数
掌握函数调用使用方法
class Singleton(object):
__instance = None
# cls代表这是个类函数;cls代表类本身
def __new__(cls, age, name):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
a = Singleton(16, 'ermao')
b = Singleton(5, 'ermao')
a.age = 2
print(b.age)
输出结果:2
熟悉常用的内置函数名和使用方法(输入参数与输出格式)
掌握类型转换概念
掌握随机函数使用方法random
from random import randint
print(randint(1, 10))
掌握数学函数包import方法和常见数学函数
掌握新函数定义和使用方法
掌握形参与实参的概念以及区别
掌握函数的返回值概念
10、文件(txt,csv,json)
#一年级要举行一个猜谜语比赛,需要从儿童谜语集中随机抽题组成5份试卷(每一份10题)
#请编写程序完成组卷,并生成试卷文件和答案文件。
import random
with open('D://7_4儿童谜语集.csv', 'r', encoding='utf-8') as f:
lines = f.readlines()
for row in range(1, 6):
for j in range(1, 11):
a = random.randint(2, 40)
word = lines[a]
question = (word.split(",")[0])
answer = (word.split(",")[-1])
print(question)
print(answer.rstrip())
with open(f"text_question{i}.txt", 'a', encoding='utf-8') as f_question:
f_question.write(question)
with open(f"text_answer{j}.txt", 'a', encoding='utf-8') as f_answer:
f_answer.write(answer)
print("\n")
掌握文件的打开、关闭方法 with as
掌握文本文件和文本行概念以及文本行读取方法
熟悉文件搜索方法
掌握try-except与open等文件检查方法
filename = 'D://aaa.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.readlines()
except FileNotFoundError:
print(f"Sorry, the file{filename} does not exits.")
else:
for line in contents:
print(line.rstrip())
掌握文件写入方法
filename='D://bbb.txt'
with open(filename, 'w') as f:
f.write("monster is the best girl!")
with open(filename,'a') as f:
f.write("be happy!\n")
掌握文件常见错误与调试方法
12、matplotlib画图
掌握折线,点状,柱状,饼状图
随机漫步,投掷骰子
扔骰子
# die.py
from random import randint
class Die:
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1, self.num_sides)
# die_visual.py
from die import Die
from plotly.graph_objs import Bar, Layout
from plotly import offline
die_1 = Die()
die_2 = Die(10)
results = []
for roll_num in range(50_000):
result = die_1.roll() + die_2.roll()
results.append(result)
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result + 1):
frequency = results.count(value)
frequencies.append(frequency)
x_values = list(range(2, max_result + 1))
data = [Bar(x=x_values, y=frequencies)]
x_axis_config = {'title': '结果', 'dtick': 1}
y_axis_config = {'title': '结果的频率'}
my_layout = Layout(title='掷一个D6和一个D10 50000次的结果', xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6_d10.html')
print(frequencies)
# 随机漫步
# rw_visual.py
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw = RandomWalk(50_000)
rw.fill_walk()
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(15,9))
point_numbers=range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none', s=1)
ax.scatter(0,0,c='green',edgecolors='none',s=100)
ax.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
keep_running = input("Make another walk?(y/n):")
if keep_running=='n':
break
# random_walk.py
from random import choice
class RandomWalk:
def __init__(self,num_points=5000):
self.num_points=num_points
self.x_values=[0]
self.y_values=[0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_distance * y_direction
if x_step == 0 and y_step == 0:
continue
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)