Python二级笔记整理

Python二级笔记整理

00讲

1. 单选:

公共基础 10分
Python语言理论 30分
20/40 60/100

2. 操作

41.基本操作题(填空)
42.简单应用题:填一部分,小段
43.综合应用题:编写一段,整个
120min 100 percentage

3.教材
4.python3.5.2以上

二级考试说明:http://www.sohu.com/a/209631763_797291
安装包/安装步骤:http://ncre.neea.edu.cn/html1/report/1807/2866-1.htm
①√Customize Installation
√Install…
②Next
③Browse
④Install
⑤Close
输入python --version

环境配置

此电脑——属性——高级系统设置——环境变量

Hello World
>>> print('Hello World')
Hello World

01讲 01章 程序设计的基本方法

导图

知识导图交互式:命令形式

程序设计语言
  1. 计算机能够理解和识别用户操作意图的一种交互体系,是计算机能够执行的计算机指令
  2. 按照程序设计语言规则组织起来的一组计算机指令(命令的集合)成为计算机程序
  3. 高级编程语言根据执行机制不同分为:
    静态语言:编译语言、文件式
    脚本语言:解释语言、交互式
  4. Python是一门脚本语言,通过解释方式进行
编译和解释
  1. 解释:一行一行翻译
    将源代码逐条翻译,逐条运行
  2. 编译:将整个程序翻译为计算机能够识别的二进制代码,然后一行一行翻译
    将整个程序翻译为目标代码
计算机编程

利用计算机,思维方法解决实际方法

Python最小程序
>>> :命令标识符
print("字符串"):打印
Python程序的运行方式
  1. 第一行:“>>>”是python语言运行环境的提示符
  2. 第二行:python语句的执行结果
  3. 3.0以前仅支持英文,3.0以后支持中文等非西文字符的直接使用
Python程序的编辑方式

通过IDLE、、、

Python程序的运行方式
  1. 交互式
    回车运行

  2. 文件式
    F5运行

>>> 
================== RESTART: D:/ing/python/python/program.py ==================
大家早上好
IPO程序编写方法
  1. 输入数据(input)
    一个程序的开始。程序要处理的数据有多种来源,形成了多种输入方式。
    包括:文件输入、网络输入、控制台输入、交互界面输出。随机数据输入、内部参数输入等

  2. 处理数据(process)
    程序对输入数据进行计算产生输出结果的过程。计算问题的处理方法统称“算法”,是程序中最重要的组成部分(一个程序的灵魂)

  3. 输出数据(output)
    程序运算成果的方式。
    包括:控制台输出、图形输出、文件输出、网络输出、操作系统内部变量输出等

Python程序的特点
  1. python具有通用性
    (python的原始开发语言是C语言,母语言)
    适合数据分析机器学习人工智能Web开发

  2. python语法简洁
    python主要用来精确表达问题逻辑,更接近自然语言,只有35个保留字,十分简洁

  3. python生态高产
    python解释器提供了几百个内置类和函数库,此外,世界各地程序员通过开源社区贡献了十几万的第三方函数库,几乎覆盖了计算机技术的各个领域,编写python程序可以大量利用已有内置或第三方代码,具备良好的编程生态

(简洁、兼容、高产)

python还具有:平台无关强制可读支持中文

python通过强制缩进(类似文章段落首行空格)来体现语句的逻辑关系。显著提高了程序的可读性,进而增强了python程序的可维护性

实例解析
缩进
#:注释语句(增强可读性)(偶合)
  1. 空格
  2. tab键
作业

1. 斐波那契数列的计算

#CalFibonacci
a,b=0,1         #0赋值给a,1赋值给b
while a <1000:  #输出不大于1000的序列
                #:表示后边还有语句
                #4个空格表示缩进
    print(a,end=",")   #输出a的值,后边加逗号 
    a,b=b,a+b   #b赋值给a,a+b赋值给b

============ RESTART: D:/ing/python/python/files/CalFibonacci.py ============
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

空格表隶属关系,命令包含在上一语句中,否则将出现错误

2. 根据圆的半径计算圆的面积

#CalCircleArea
r=25    #圆的半径是25
area=3.1415*r*r
print(area)
print("{:.2f}".format(area))    #只输出两位小数


============ RESTART: D:/ing/python/python/files/CalCircleArea.py ============
1963.4375000000002
1963.44

3. 用python绘制一个五角红星图形

#DrawStar
from turtle import*
color('red','red')
begin_fill()
for i in range(5):
    fd(200)
    rt(144)
end_fill()
done()

DrawStar

4. 对一个循环计数一千万次的程序记录并输出其运行时间

#CalRunTime
import time
limit=10*1000*1000
start=time.perf_counter()
while True:
    limit-=1
    if limit<=0:
        break
delta=time.perf_counter()-start
print("程序运行时间是:{}秒".format(delta))


============= RESTART: D:/ing/python/python/files/CalRunTime.py =============
程序运行时间是:1.246567秒

5. 绘制7个不同颜色的圆圈,组成器材圆圈图案

#DrawSevenColorfulCircles
import turtle
colors=['red','orange','yellow','green','blue','indigo','purple']
for i in range(7):
    c=colors[i]
    turtle.color(c,c)
    turtle.begin_fill()
    turtle.rt(360/7)
    turtle.circle(50)
    turtle.end_fill()
turtle.done()

DrawSevenColorfulCircles

02讲 02章 Python语言基本语法元素

考纲考点
  1. 程序的基本语法元素:程序的格式框架、缩进、注释、变量、命名、保留字、数据类型、赋值语句、引用
  2. 基本输入输出函数:input()、eval()、print()
  3. 源程序的书写风格
知识导图

程序的格式框架
缩进
  1. python语言采用严格的“缩进”来表明程序的格式框架,表示包含和层次关系
  2. 1个缩进 = 4个空格 = tab键 两者不能混用
  3. 缩进是Python语言中表明程序框架的唯一手段
  4. 当表示分支、循环、函数、类等程序含义时,在 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&timestamp=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
          #没有被定义过
保留字
  1. “关键字”,被编程语言内部定义并保留的标识符
  2. 程序员编写程序不能定义与保留字相同的标识符
  3. 每种程序设计语言都有一套保留字,保留字一般用来构成程序整体框架,表达关键值和具有结构性的复杂语义等
  4. 掌握一门编程语言首先要熟记其所对应的保留字

python3.x保留字列表

序号保留字说明
1and用于表达式运算,逻辑与操作
2as用于类型转换
3assert断言,用于判断变量或条件表达式的值是否为真
4async
5await
6break中断循环语句的执行
7class用于定义类
8continue继续执行下一次循环
9def用于定义函数或方法
10del删除变量或序列的值
11elif条件语句,与 if,else 结合使用
12else条件语句,与 if,elif结合使用,也可以用于异常和循环语句
13except包含捕获异常后的操作代码块,与 try,finally 结合使用
14False
15finally用于异常语句,与 try,except 结合使用
16forfor循环
17form用于导入模板,与 import 结合使用
18global定义全局变量
19if条件语句,与 else,elif 结合使用
20import多用于导入模板,与 form 结合使用
21in判断变量是否在序列中
22is判断变量是否为某个类的实例
23lambda定义匿名函数
24None
25nonlocal
26not用于表达式运算,逻辑非操作
27or用于表达式运算,逻辑或操作
28pass空的类,方法或函数的占位符
29raise异常抛出操作
30return用于函数返回计算结果
31Ture
32trytry包含可能出现异常的语句,与 except,finally 结合使用
33while循环语句
34with简化 python 的语句
35yield用于从函数依次返回值
数据类型

简单:数字类型,字符串类型
略微复杂:元组类型,集合类型,列表类型

数字类型

表示数字或数值的数据类型(整数、浮点数(实数)、复数)

整数值
二进制:0b
八进制:0o
十进制:1010=1×103+0×102+1×10^1+0
十六进制:0x3F2=3×162+15×161+2
eg:0x17=16+7=23

101112131415
ABCDEF
>>> 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
HelloWorld
012345678910

正向递减序号

>>> "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)

其他语句
分支语句
循环语句

作业
  1. 获得用户输入的一段文字,将这段文字进行垂直输出
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 =================
请输入一段文本:中华人民共和国
中
华
人
民
共
和
国
  1. 获得用户输入的一个实数,提取并输出其小数部分
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
  1. 时针代码
    (输入有误,待检查)
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()

03讲 基本输入输出函数

基本输入输出函数
input()函数

可以输入一些包含提示性的文字

>>> input()
123
'123'

>>> input("请输入一个数")
请输入一个数45
'45'

>>> a=input("abc")
abc78
>>> a
'78'
  #通过input函数获取的数据都是字符串

>>> input()+45
45
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    input()+45
TypeError: Can't convert 'int' object to str implicitly
>>> input()+"45"
45
'4545'
>>> input()*5
45
'4545454545'

>>> a=input()
45
>>> a
'45'
>>> type(a)
<class 'str'>

>>> input("请输入您的成绩")
```请输入您的成绩78
'78'
eval(函数)

将字符串转化为数值

>>> a=eval("1.2+3.4")
>>> print(a)
4.6
>>> eval(input("输入成绩"))
输入成绩45
45
>>> eval(input("输入成绩"))+44
输入成绩45
89

eval 和 input 乘法比较

>>> value = eval(input("请输入要计算的数值"))
请输入要计算的数值1024.256
>>> print(value*2)        #数乘运算
2048.512

>>> input()*2              #重复
1024.256
'1024.2561024.256'

【真题】关于 eval 函数,以下选项中描述 错误 的是
A:eval 函数定义为:eval(source,globals = None,locals = None,/)
B:eval 函数的作用是将输入的字符串转为 Python 语句,并执行该语句
C:执行 “>>>eval(“Hello”)” 和 执行 “>>>eval(““Hello””)” 得到的相同的结果
D:如果用户希望输入一个数字,并用程序对这个数字进行计算,可以采用 eval(input(<输入提示字符串>))

双引号和单引号会嵌套结合 “”“” 1,3结合

print()函数
  1. 字符串
>>> print("世界和平")
世界和平
  1. 多个变量
>>> value = 123.456
>>> print(value, value, value)
123.456 123.456 123.456
  1. 混合输出字符串与变量值
    print(<输出字符串模板>。format(<变量1>,<变量2>,……<变量n>))
>>> age=18
>>> age
18
>>> print("今年我{}岁".format(age))
今年我18岁


>>> a,b=123.456,1024
>>> print("数字{}和数字{}的乘积是{}".format(a,b,a*b))
数字123.456和数字1024的乘积是126418.944

间隔
print(<待输出内容>,end="<增加的输出结尾>")

>>> age=18
>>> print(18,47,54)
18 47 54
>>> num=172
>>> print(age,num)
18 172


>>> a=47
>>> print(a,end=".")
47.

【真题】给出如下代码 TempStr=“Hello World”可以输出“World”的是
√ A:print(TempStr[-5:])
B:print(TempStr[-5:-1])
C:print(TempStr[-4:-1])
D:print(TempStr[-5:0])

>>> a="Hello World"
>>> a[-5:]        #从-5位置到结尾
'World'
>>> a[2:]
'llo World'
>>> a[-5:-1]
'Worl'
>>> a[0:3]
'Hel'
>>> a[-5:0]
''          #两种方法不能交叉使用

04讲 实例解析和作业

案例4-1

逆序

s=input("请输入一段文本:")
i=len(s)-1        #测试字符串长度,长度-1表示最后一个字符
while i>=0:
    print(s[i],end=" ")        #s[i]:字符串切片,表示一个元素
    i=i-1             #循环


================= RESTART: D:/ing/python/python/files/4-1.py =================
请输入一段文本:Hello World
d l r o W   o l l e H       #逆向输出
s=input("请输入一段文本:")
i=len(s)-1          #s[4],s[3],s[2]……逆序
while i>=0:
    print(s[i])      #默认间隔符是回车(换行)
    i=i-1


================= RESTART: D:/ing/python/python/files/4-1.py =================
请输入一段文本:Hello World
d
l
r
o
W
 
o
l
l
e
H

正序

s=input("请输入一段文本:")
i=len(s)
j=0
while j<i:
    print(s[j])
    j=j+1

================= RESTART: D:/ing/python/python/files/4-1.py =================
请输入一段文本:Hello World
H
e
l
l
o
 
W
o
r
l
d
s=input("请输入一段文本:")
i=len(s)
j=0
while j<i:
    print(s[j],end=" ")
    j=j+1

================= RESTART: D:/ing/python/python/files/4-1.py =================
请输入一段文本:Hello World
H e l l o   W o r l d 

######案例4-2

s=input("请输入一段文本:")
i=-1    #从-1开始
while i>=-1*len(s):    #-1乘长度
    print(s[i],end="")
    i=i-1


================= RESTART: D:/ing/python/python/files/4-2.py =================
请输入一段文本:Hello World
dlroW olleH

输出小数部分

>>> a=1.2345
>>> int(a)      #取整函数
1

>>> a=7.77777
>>> round(a,4)      #四舍五入函数
7.7778

int() 取整
round() 四舍五入

05讲 03章 基本数据类型

考纲考点

数字类型:整数类型、浮点数类型(实数)、复数类型
数字类型运算:数值运算操作符、数值运算函数
字符串类型及格式化:索引、切片、基本的format()格式化方法
字符串类型的操作:字符串操作符、处理函数和处理方法
类型判断和类型间转换

数字类型

整数类型:整数:1010
浮点数类型:实数:10.10
复数类型:复数:10+10j

数字类型
>>> a=10
>>> type(a)
<class 'int'>      #类型为整形,int()是整形简写

>>> b=0.123
>>> type(b)
<class 'float'>      #浮点型

>>> type(1+2j)
<class 'complex'>    #复数型

进制种类引导符号描述算式
十进制默认情况,eg:1010,-10109+1=10
二进制0b 或 0B由字符 0 和 1 组成,eg:0b1010,0B10101+1=10
八进制0o 或 0O由字符 0 到 7 组成,eg:0o1010,0O10107+1=10
十六进制0x 或 0X由字符 0 到 9,a 到 f 或 A 到 F 组成,eg:0x10108+8=10
>>> 0o10
8
>>> 0x16
22
>>> 0xf
15

不同进制的整数之间可以直接运算
(十进制数转化为非十进制数)

>>> bin(4)
'0b100'
>>> oct(10)
'0o12'
>>> hex(15)
'0xf'

>>> 0xf+5
20
浮点数类型

必须带有小数部分,小数部分可以是0,
表示方法:一般表示、科学计数法(仅限十进制,非十进制数没有浮点数类型)

科学计数法使用 e 或 E 作为幂的符号,以10为基数
含义:< a > e < b > = a × 10 b

>>> 3e3
3000.0      #3×10^3
复数类型

j 是虚数单位
a+bjb=0或1都不能省略

【真题】关于Python的数字类型,一下选项中描述
错误 的是
A:整数类型的数值一定不会出现小数点
√ B:浮点数也有十进制、二进制、八进制和十六进制等表示方式
C:1.0是浮点数,不是整数
D:复数类型虚部为0时,表示为1+0j

06讲 数字类型数据的操作符和函数

数字类型运算
数值运算操作符
操作符描述
x + yx 与 y 之和
x - yx 与 y 之差
x * yx 与 y 之积
x / yx 与 y 之商
x // yx 与 y 之整数商,eg:不大于想 x 与 y 之商的最大整数
x % yx 与 y 之商的余数,也称模运算(求余)
- xx 的负值,即 x*(-1)
+ xx 本身
x ** yx 的 y 次幂,即 x^(y)
>>> 5/3
1.6666666666666667
>>> 5//3      #整除
1

>>> 2%3      #余数
2
>>> 4%2
0
>>> 2**3
8

>>> a=2
>>> a**3      #复合运算(二元运算)
8

op 表示二元运算操作符

# x op=y 等价于 x=x op y
>>> x=99
>>> x**=3
>>> print(x)
970299

# x**=3 等价于 xx**3

>>> x=99
>>> x=x**3
>>> print(x)
970299

数值运算操作符
整数与浮点数混合运算,输出结果是浮点数
整数或浮点数与复数运算,输出结果是复数

数值运算函数

功能、语法

函数描述
abs(x)x 的绝对值
divmod(x,y)(x//y,x%y),输出为二元组形式(也称为元组类型))
pow(x,y[,z])(x ** y)%z,[…]表示该参数可以省略,即:pow(x,y)与x**y相同
round(x[,ndigits])对 x 四舍五入,保留 ndigits 位小数,round(x) 返回四舍五入的整数值,省略小数位,则为取整
max(x1,x2,…,xn)x1,x2,…,xn 的最大值,n 没有限定
min(x1,x2,…,xn)x1,x2,…,xn 的最小值,n 没有限定
>>> a=2
>>> abs(a)
2
>>> divmod(4,2)      #divmod(x,y)  x是商,y是余数
(2, 0)
>>> pow(2,3)        #2^(3)=8
8
>>> pow(2,3,3)      #2^(3)=8,8与3之商的余数=2
2

【真题】下面代码的输出结果是
x=10
y=3
print(x%y,x ** y)
A:1 30
√ B:1 1000
C:3 30
D:3 1000
解:10求余3=1,10^(3)=1000

【真题】下面代码的输出结果是
a=5
b=6
c=7
print(pow(b,2)-4 * a * c)
A:104
B:系统报错
C:36
√ D:-104
解:6^(2)=36,36-4ac=-104

07讲 字符串数据类型的介绍和字符串数据索引和切片及format的基本应用

字符串类型及格式化
字符串类型
>>> type("2")
<class 'str'>      #字符串类型,加 “ ”
>>> a="abc"
>>> type(a)
<class 'str'>

运行错误(就近组合,无效字符)

>>> a="She said"Hello World""
SyntaxError: invalid syntax

边界符:单引号

>>> a="She said'Hello World'"
>>> a
"She said'Hello World'"

三引号
三引号换行运行

>>> a="""Hello
World"""
>>> a
'Hello\nWorld'      #\n表示换行,回车

>>> a="Hello      
SyntaxError: EOL while scanning string literal

Python语言转义符:
eg:\n 表示换行,\ 表示反斜杠,’ 表示单引号,\t 表示制表符(TAB等)

>>> "\'"
"'"
>>> "'"
"'"
>>> '\''
"'"
>>> '''

字符串索引
>>> a="World"
>>> a[3]
'l'
>>> a[-2]
'l'
>>> a[-3]
'r'

>>> "World"[3]
'l'
字符串切片
>>> a="World"
>>> a[1:3]
'or'
>>> a[3:]
'ld'
>>> a[:2]
'Wo'
>>> a[-1:-3]
''
>>> a[-3:-1]
'rl'

单向计数

>>> a="World"
>>> a[1,-3]
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    a[1,-3]
TypeError: string indices must be integers
format() 方法的基本使用
>>> a="Mstmxly"
>>> "I am {}".format(a)
'I am Mstmxly'
>>> b="Shirley"
>>> "I am {} or {}".format(a,b)
'I am Mstmxly or Shirley'
>>> "I am {1} or {0}".format(a,b)
'I am Shirley or Mstmxly'

>>> a="Shirley"
>>> b="student"
>>> "{} is a {}".format(a,b)
'Shirley is a student'

>>> "{0} is a {1}".format(a,b)
'Shirley is a student'
>>> "{1} is a {0}".format(a,b)
'student is a Shirley'

08讲 format 格式控制

format() 方法的格式控制
<填充><对齐><宽度>.<.精度><类型 >
引导符号用于填充的单个字符<左对齐 >右对齐 ^居中对齐横的设定输出宽度数字的千位分隔符,适用于整数和浮点数浮点数小数部分的精度或字符串的最大输出长度整数类型b,c,d,o,x,X,浮点数类型e,E,f,%

b:输出整数的二进制方式
c:输出整数对应的 Unicode 字符
d:输出整数的十进制方式
o:输出整数的八进制方式
x:输出整数的小写十六进制方式
X:输出整数的大写十六进制方式

>>> "{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(425)
'110101001,Ʃ,425,651,1a9,1A9'
>>> "{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(45)
'101101,-,45,55,2d,2D'
>>> "{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(15)
'1111,\x0f,15,17,f,F'

e:输出浮点数对应的小写字母 e 的指数形式
E:输出浮点数对应的大写字母 E 的指数形式
f:输出浮点数的标准浮点形式
%:输出浮点数的百分形式

>>> "{0:e},{0:E},{0:f},{0:%}".format(3.14)
'3.140000e+00,3.140000E+00,3.140000,314.000000%'

>>> "{0:.2e},{0:.2E},{0:.2f},{0:.2%}".format(3.14)
'3.14e+00,3.14E+00,3.14,314.00%'
>>> "{:.2f}".format(3.1415926)          #输出小数点后两位
'3.14'
>>> "{:x}".format(1010)         #输出整数的十六进制形式
'3f2'
>>> "{:.5}".format("so long")         #输出字符串的前 5 位
'so lo'
>>> "{:-^10}".format("python")         #居中并填充
'--python--'
>>> s="等级考试"
>>> "{}".format(s)
'等级考试'
>>> "{:>}".format(s)
'等级考试'
>>> "{:>15}".format(s)          #左对齐
'           等级考试'
>>> "{:<15}".format(s)          #右对齐
'等级考试           '
>>> "{:*<15}".format(s)          #填充*
'等级考试***********'
>>> "{:*<.3}".format(s)          # .3 精度
'等级考'
>>> "{:*<.3}".format(123.456)
'1.23e+02'
>>> "{:.3}".format(123.456)
'1.23e+02'
>>> "{:.2}".format(123.456)
'1.2e+02'
>>> "{:.3f}".format(123.456)
'123.456'
>>> "{:.2f}".format(123.456)      #有四舍五入功能
'123.46'

注:
字符宽度小于指定宽度,默认增加空格达到指定宽度;
字符宽度大于指定enter宽度,则完整输出字符宽度。

【真题1】给出如下代码
s="Alice"
print(s[::-1])
上述代码的输出结果是
A:Alice
B:ALICE
√ C:ecilA
D:Alic
注:数据起点,终点,步长

>>> a="abcdefg"
>>> a[2:3]
'c'
>>> a[2:4]
'cd'
>>> a[1:6:2]
'bdf'

【真题2】给出如下代码
s="abcdefghijklmn"
print(s[1:10:3])
上述代码的输出结果是
A:beh
B:adg
C:behk
D:adgj

【真题3】给出如下代码
a="Python"
b="A Superlanguage"
print("{:->10}:{:-<19}".format(a,b))
上述代码的输出结果是
A:----Python:----A Superlanguage
B:Python----:----A Superlanguage
C:The python language isa multimodel language
√ D:----Python:A Superlanguage----

>>> a="Python"
>>> b="A Superlanguage"
>>> print("{:->10}:{:-<19}".format(a,b))
----Python:A Superlanguage----
        #{:->10} - 填充符 >右对齐 10宽度
        #单个字符填充,右对齐,宽度为10个
        #{:-<19}    左对齐,宽度为19

09讲 字符串函数和方法

字符串类型的操作
操作符描述
x + y连接两个字符串 x 与 y
x * n 或 n * x复制 n 次字符串 x
x in y如果 x 是 s 的子串,返回 Ture,否则返回 False
>>> "aaa"+"bbb"
'aaabbb'
>>> 12+24
36
>>> "aaa"+24
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    "aaa"+24
TypeError: Can't convert 'int' object to str implicitly

>>> "abc"*2
'abcabc'
>>> "555"*2
'555555'
>>> 555*2
1110
>>> "ab"in"abcd"
True
字符串处理函数
函数描述
len()返回字符串 x 的长度,也可返回其他组合数据类型的元素个数
str()返回任意类型 x 所对应的字符串形式
chr()返回 Unicode 编码 x 对应的单字符
ord()返回单字符 x 表示的 Unicode 编码
hex()返回整数 x 对应十六进制数的小写形式字符串
oct()返回整数 x 对应八进制数的小写形式字符串
>>> a="Hello"
>>> len(a)
5
>>> len("Hello世界")
7
>>> str(123)
'123'
>>> chr(65)
'A'
>>> ord("A")
65
>>> hex(17)
'0x11'
>>> oct(9)
'0o11'
字符串处理方法

方法也是一个函数,只是调用方式不同。函数采用 fun() 方式调用,而方法则采用 .fun(x) 形式调用。方法仅作用于前导对象。

方法描述
str.lower()返回字符串 str 的副本,全部字符小写
str.upper()返回字符串 str 的副本,全部字符大写
str.split(sep=None)返回一个列表,由 str 根据 sep 被分割的部分构成,省略 sep 默认以空格分隔
str.count(sub)返回sub子串出现的次数
str.replace(old,new)返回字符串 str 的副本,所有 old 子串被替换为 new
str.center(width,fillchar)字符串居中函数,fillchar 参数可选
str.strip(chars)从字符串 str 中去掉在其左侧和右侧 chars 中列出的字符
str.join(iter)将 iter 变量的每一个元素后增加一个 str 字符串
>>> a="ABD"
>>> a.lower()
'abd'
>>> "ACD".lower()
'acd'

>>> a      #返回值为副本,不改变原始参数
'ABD'

>>> a="ab cd ek"
>>> a.split()    #默认分隔
['ab', 'cd', 'ek']        # []表示列表型数据

>>> a
'ab cd ek'
>>> a.split("d")      #从"d"处分隔
['ab c', ' ek']

>>> type(a)
<class 'str'>          #类型发生改变
>>> type(a.split())
<class 'list'>

>>> "abbcabdd455".count("ab")
2          #"ab"的出现次数

>>> "abcdefgx".replace("cd","**")
'ab**efgx'      #"**"替换"cd"

>>> "ab".center(10)
'    ab    '      #ab前后各四个空格,总的十个字符

>>> "abcdab".strip("ab")
'cd'
>>> "abcabdab".strip("ab")
'cabd'        #删除左侧或右侧的字符串,中间的需要先分隔,再删除

>>> "abc".join("*")
'*'
>>> "*".join("abcd")
'a*b*c*d'        #顺序不能反

【真题】下面代码的输出结果是
s="The python language is a cross platform language."
print(s.find(“language”,30))
A:系统报错
B:10
C:11
√ D:40

>>> s="The python language is a cross platform language."
>>> print(s.find("language",30))
40
# find:查找。
#在s里边查找language的出现位置。30:从第30个字符开始数。
>>> print(s.find("language"))
11

#str.find()查询子串在大串中的位置
>>> "abcde".find("c")
2

【真题】下面代码的输出结果是
s="The python language is a multimodel language."
print(s.split( ))
A:系统报错
B:The python language is a multimodel language.
C:Thepythonlanguageisamultimodellanguage.
√ D:[‘The’, ‘python’, ‘language’, ‘is’, ‘a’, ‘multimodel’, ‘language.’]

【真题】下面代码的输出结果是
str1='mysqlsqlserverPostgresQL’
str2='sql’
ncount=str1.count(str2)
print(ncount)
A:3
B:4
√ C:2
D:5
(注:str2在str1中出现的次数)
ASCII值不相等:A=65,a=97→A≠a

10讲 实例解析

类型判断和类型间转换
数字类型的转换
>>> a=input("请输入一个数")
请输入一个数5
>>> a
'5'
>>> type(a)
<class 'str'>
>>> eval("45")+1
46
>>> eval(a)+5
10
n=eval(input('请输入一个数:'))
if type(n)==type(123):
    print("输入的数字是整数。")
elif type(n)==type(11.3):
    print("输入的数字是浮点数。")
else:
    print("无法判断输入类型。")
函数描述
int(x)将x转换为整数,x可以是浮点数或字符串
float(x)将x转换为浮点数,x可以是整数或字符串
str(x)将x转换为字符串,x可以是整数或浮点数
n=eval(input("请输入一个数字:"))
if n==int(n):
    print("整数")
=============== RESTART: D:/ing/python/python/files/example.py ===============
请输入一个数字:45
整数
实例解析
凯撒密码

C=(P+3) mod 26

# CaesarEncode.py
ptxt = input("请输入明文文本: ")
for p in ptxt:
    if "a" <= p <= "z":
        print(chr(ord("a")+(ord(p)-ord("a")+3)%26), end='')
    elif "A" <= p <= "Z":
            print(chr(ord("A")+(ord(p)-ord("A")+3)%26), end='')
    else:
            print(p, end='')

============= RESTART: F:\Python2\行文代码\行文代码\第3章\CaesarEncode.py =============
请输入明文文本: Hello World
Khoor Zruog

============= RESTART: F:\Python2\行文代码\行文代码\第3章\CaesarEncode.py =============
请输入明文文本: ABC
DEF

注释

#ord(p):p在字母表中的排序
#+3:加密
#%26:求余
#ord("a"):明文的ASCII值
#(ord(p)-ord("a")+3)%26:编号
#ord("a")+(ord(p)-ord("a")+3)%26:加密后的值
#chr():将ASCII值转编为字母
#end='':默认输出为换行,每运行一次换一行

>>> ord("A")
65
>>> chr(65)
'A'
解密

P=(C-3) mod 26

# CaesarDecode.py
etxt = input("请输入加密后文本: ")
for p in etxt:
    if "a" <= p <= "z":
        print(chr(ord("a")+(ord(p)-ord("a")-3)%26), end='')
    elif "A" <= p <= "Z":
            print(chr(ord("A")+(ord(p)-ord("A")-3)%26), end='')
    else:
            print(p, end='')

============= RESTART: F:\Python2\行文代码\行文代码\第3章\CaesarDecode.py =============
请输入加密后文本: Khoor Zruog
Hello World

============= RESTART: F:\Python2\行文代码\行文代码\第3章\CaesarDecode.py =============
请输入加密后文本: ABC
XYZ
原文ABCDE
密文DEFGH

eg:
ASCII: C=67
67+3=70
70÷26=2…18
(求余:70%26=18)
错误)不用ASCII值计算,应该用当前字母在字母表中的顺序

【作业】输入一个浮点数,将它的整数部分连续输出三次

a=eval(input("please input num:"))
print(str(int(a))*3)
=============== RESTART: D:/ing/python/python/files/example.py ===============
please input num:65
656565

【作业】输入两个字符串,判断其中一个字符串在另一个字符串中出现的次数

a,b=input("a"),input("b")
print(a.count(b))
=============== RESTART: D:/ing/python/python/files/example.py ===============
a
b
1

11讲 04章 程序结构之分支结构

程序的控制结构
考纲

程序的三种控制结构:顺序、分支、循环
程序的分支结构:单分支结构、二分支结构、多分支结构
程序的循环结构:遍历循环、无限循环、break循环和continue循环控制
程序的异常处理:try-except

课本
>>> a=input("")
45
>>> a
'45'
>>> type(a)
<class 'str'>
#字符串型数据,不能进行求余计算
>>> a=eval(input(""))
45
>>> a
45
>>> type(a)
<class 'int'>
#数值型数据
a=eval(input("请输入一个数"))
if a%3==0 and a%5==0:
    print("OK")
else:
    print("不OK")

=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个数20
不OK

=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个数30
OK
#输入一个成绩,判断它属于哪个层次
s=eval(input("请输入一个成绩"))
if s>=90:
    print("优秀")
elif s>=80:
    print("良好")
elif s>=60:
    print("及格")
else:
    print("不及格")

=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个成绩64
及格

=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个成绩92
优秀

12讲 程序结构之异常处理

程序的循环结构

遍历循环无限循环
遍历循环:使用保留字 for 依次提取比遍历结构各元素进行处理
无限循环:使用保留字 while 根据判断条件执行程序

遍历循环:使用保留字 for 依次提取遍历结构各元素进行处理
for <循环变量> in <遍历结构>
    <语法块>


a="abcd"
for b in a:
    print(b)
=============== RESTART: D:\ing\python\python\files\example.py ===============
a
b
c
d


s=0
for i in range(10):
    s=s+i
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
45    #求和过程中不包括10(切片)


s=0
for i in range(10):
    s=s+i
    print(i)
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
0
1
2
3
4
5
6
7
8
9
45


s=0
for i in range(11):
    s=s+i
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
55

无限循环:使用保留字while 根据判断条件执行程序

有条件终止循环,不是死循环

while <条件>:
      <语句块>


n=0
while n<10:
    print(n)
    n=n+3
=============== RESTART: D:\ing\python\python\files\example.py ===============
0
3
6
9


s=0
i=0
while i<11:
    s=s+i        #等价于s+=i
    i+=1        #等价于i=i+1
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
55


s=0
i=0
while i<11:
    s=s+i
    i+=1
else:
    print("计算完毕")
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
计算完毕
55
循环控制:break 和 continue
#求素数(质数),也就是只能被1和本身整除的数
s=eval(input("请输入一个数"))
i=2
#while
while i<s:
    if s%i==0:
        print("非素数")
        break   #终止循环
    i+=1
else:
    print("素数")
=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个数7
素数
素数
素数
素数
素数
素数
素数
#求素数(质数),也就是只能被1和本身整除的数
#输入一个数,输出从2开始到这个数之间的素数
s=eval(input("请输入一个数"))
for j in range(2,s):
    i=2
    #while
    while i<j:
        if j%i==0:
            print("非素数",j)
            break   #终止循环
        i+=1
    else:
        print("素数",j)
=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个数8
素数 2
素数 3
非素数 4
素数 5
非素数 6
素数 7

【真题】
continue

for s in "HelloWorld":
    if s=="W":
        continue
    print(s,end="")
=============== RESTART: D:\ing\python\python\files\example.py ===============
Helloorld
for s in "HelloWorld":
    if s=="W":
        break
    print(s,end="")
=============== RESTART: D:\ing\python\python\files\example.py ===============
Hello
for i in "Python":
    print(i,end="")
=============== RESTART: D:\ing\python\python\files\example.py ===============
Python
for i in "Python":
    print(i)
=============== RESTART: D:\ing\python\python\files\example.py ===============
P
y
t
h
o
n
a=3
while a>0:
    a-=1
    print(a,end="")
=============== RESTART: D:\ing\python\python\files\example.py ===============
210
age=23
start=2
if age%2!=0:
    start=1      # 步长为1
for x in range(start,age+2,2):
    print(x)
=============== RESTART: D:\ing\python\python\files\example.py ===============
1
3
5
7
9
11
13
15
17
19
21
23
k=10000
while k>1:
    print(k)
    k=k/2
=============== RESTART: D:\ing\python\python\files\example.py ===============
10000
5000.0
2500.0
1250.0
625.0
312.5
156.25
78.125
39.0625
19.53125
9.765625
4.8828125
2.44140625
1.220703125
for i in range(1,6):
    if i%3==0:
        break
    else:
        print(i,end="")
=============== RESTART: D:\ing\python\python\files\example.py ===============
12
sum=0
for i in range(0,100):
    if i%2==0:
        sum-=i
    else:
        sum+=i
print(sum)
=============== RESTART: D:\ing\python\python\files\example.py ===============
50
for a in ["torch","soup","bath"]:
    print(a)
=============== RESTART: D:\ing\python\python\files\example.py ===============
torch
soup
bath

13讲 程序结构之异常处理

程序的异常处理
import random
target = random.randint(1,1000)
#引用random第三方库,然后产生一个1到1000之间的随机数存储到target变量中
count = 0        #统计猜的次数
while True:        #死循环
    guess = eval(input('请输入一个猜测的整数(1至1000):'))
    count = count + 1
    if guess > target:
        print('猜大了')
    elif guess < target:
        print('猜小了')
    else:
        print('猜对了')
        break
print("此轮的猜测次数是:", count)
=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个猜测的整数(1至1000):923
猜大了
请输入一个猜测的整数(1至1000):500
猜大了
请输入一个猜测的整数(1至1000):200
猜大了
请输入一个猜测的整数(1至1000):50
猜大了
请输入一个猜测的整数(1至1000):20
猜大了
请输入一个猜测的整数(1至1000):5
猜小了
请输入一个猜测的整数(1至1000):15
猜小了
请输入一个猜测的整数(1至1000):18
猜大了
请输入一个猜测的整数(1至1000):17
猜大了
请输入一个猜测的整数(1至1000):16
猜对了
此轮的猜测次数是: 10

作业:求1到30之间素数之和,并输出每个素数


14讲 05章 素数和函数的定义和使用

05章 函数和代码复用
考纲

函数的定义和使用
函数的参数传递:可选参数传递、参数名称传递、函数的返回值
变量的作用域:局部变量和全局变量

函数的基本使用
函数的定义:def

具有特定功能的、可重用的语句组,通过函数名来表示和调用,经过定义,一组语句等价于一个函数,在需要使用这组语句的地方,直接调用函数名即可。因此,函数的使用包括两部分:函数的定义和函数的使用。

def <函数名>(<参数列表>):
    <函数体>
    return<返回值列表>
#定义一个对整数 n 求阶乘的函数
def fact(n):
    s=1
    for i in range(1,n+1):
        s *=i
    return s
#调用整数阶乘的函数
print(fact(100))
=============== RESTART: D:\ing\python\python\files\example.py ===============
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

15讲 函数的参数和返回值

函数的参数传递
可选参数传递
def <函数名>(<非可选参数列表>,<可选参数>=<默认值>):
    <函数体>
    return<返回值列表>
def multiply(x,y=10):      #定义函数
              #x是必选参数,y是可选参数,y的默认值是10
    print(x*y)
=============== RESTART: D:\ing\python\python\files\example.py ===============
>>> multiply(99)        #执行部分,99赋值给x
990
>>> multiply(99,2)        #x=99,y=2
198
def max(a,b):
    if a>b:
        return a      #一个函数中允许有多个return语句
    else:
        return b
print(max(4,5))
=============== RESTART: D:\ing\python\python\files\example.py ===============
5
参数名称传递
def multiply(x,y=10):
    print(x*y)
multiply (y=2,x=99)
=============== RESTART: D:\ing\python\python\files\example.py ===============
198
函数的返回值
def multiply(x,y=10):
    return x*y,x+y
s=multiply(99,2)
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
(198, 101)
局部变量
def multiply(x,y=10):
    z=x*y   #z是函数内部的局部变量
    return z
s=multiply(99,2)
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
198
全局变量
n=2    #n是全局变量
def multiply(x,y=10):
    global n  
    return x*y*n    #使用全局变量n
s=multiply(99,2)
print(s)
=============== RESTART: D:\ing\python\python\files\example.py ===============
396
def greeting(args1,*tupleArgs,**dictArgs):
    print(args1)
    print(tupleArgs)
    print(dictArgs)
names=["HTY","LFF","ZH"]                    #列表型数据
info={"schoolName":"NJRU","City":"Nanjing"} #字典型数据
greeting(*names,'Hello,',**info)
=============== RESTART: D:\ing\python\python\files\example.py ===============
HTY
('LFF', 'ZH', 'Hello,')
{'schoolName': 'NJRU', 'City': 'Nanjing'}

16讲 函数的局部和全局变量,代码利用和实例解析

代码复用

【真题】

#递归调用方法求阶乘
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)
num=eval(input("请输入一个整数:"))
print(fact(abs(int(num))))    #print(调用函数(求绝对值(取整)))
=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个整数:5
120
=============== RESTART: D:\ing\python\python\files\example.py ===============
请输入一个整数:3
6

eg:n=2

n=23210
if:×××return 1
else:3×f(2)3×2×f(1)3×2×1×f(0)3×2×1×1=6
#循环语句求阶乘
def fact(n):    #fact(n)函数功能是求n的阶乘
                #n为必选参数。if:n=3为可选参数
    s=1         #s是局部变量,在函数内部定义
    for i in range(1,n+1):  #range()函数是python的内置函数
        s*=i
    return s
=============== RESTART: D:\ing\python\python\files\example.py ===============
#累加
def fib(n):
    a,b=1,1
    for i in range(n-1):
        a,b=b,a+b
    return a
print(fib(7))
================= RESTART: D:\ing\python\python\files\eg.py =================
13

【实例】软文的诗词风

txt = '''
人生得意须尽欢,莫使金樽空对月。
天生我材必有用,千金散尽还复来。
'''         #三引号:多行字符串
linewidth = 30  # 预定的输出宽度

def lineSplit(line):        #把标点替换成回车
    plist = [',', '!', '?', ',', '。', '!', '?']     #列表数据类型,相当于数组
    for p in plist:
        line = line.replace(p, '\n')    #替换,把标点符号换成换行\n
    return line.split('\n')             #按回车进行分割
    
def linePrint(line):
    global linewidth
    print(line.center(linewidth, chr(12288)))   #按30个字符的宽度进行居中

newlines = lineSplit(txt)
for newline in newlines:
    linePrint(newline)
================= RESTART: D:\ing\python\python\files\eg2.py =================
                              
           人生得意须尽欢            
           莫使金樽空对月            
                              
           天生我材必有用            
           千金散尽还复来            
                              
                              

分解

>>> a="中国人\n美国人\n英国人\n"
>>> type(a) 
<class 'str'>      #类型为字符串类型
>>> a.split("\n")      #对a的数据进行分割,按照 \n 来分割
['中国人', '美国人', '英国人', '']
>>> type(a)      #分割不会改变a的值,仅做分割处理,副本
<class 'str'>
>>> b=a.split("\n")      #b为列表型数据
<class 'list'>

>>> for x in b:      #x从b变量b是列表型数据)中每次读取一个字符串
	print(x)

中国人
美国人
英国人
txt = '''
三国演义 上卷
罗贯中

滚滚长江东逝水,浪花淘尽英雄。是非成败转头空。青山依旧在,几度夕阳红。
白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢。古今多少事,都付笑谈中。
--调寄《临江仙》
第一回 宴桃园豪杰三结义 斩黄巾英雄首立功
话说天下大势,分久必合,合久必分。周末七国分争,并入于秦。及秦灭之后,楚、汉分争,又并入于汉。
汉朝自高祖斩白蛇而起义,一统天下,后来光武中兴,传至献帝,遂分为三国。
'''
linewidth = 30

def lineSplit(line):
    plist = [',', '!', '?', ',', '。', '!', '?']
    for p in plist:
        line = line.replace(p, '\n')
    return line.split('\n')
    
def linePrint(line):
    global linewidth
    print(line.center(linewidth, chr(12288)))

newlines = lineSplit(txt)
for newline in newlines:
    linePrint(newline)
================= RESTART: D:\ing\python\python\files\eg2.py =================
略

【作业1】

#利用函数找三个数里的最大数
def max(a,b):
    if a>b:
        return a
    else:
        return b
print(max(max(4,5),6))
================= RESTART: D:\ing\python\python\files\eg.py =================
6

【作业2】

#编写一个函数,利用递归计算出斐波那契数列第n个数并返回
def fab(n):
    if n<3:
        return 1
    return(fab(n-1)+fab(n-2))
print(fab(10))
================= RESTART: D:\ing\python\python\files\eg.py =================
55

【作业3】

#编一个函数,计算字符串中数字、字母、空格及其他字符的个数
def count(str1):
    num_number=char_number=space_number=other_number=0
    for char in str1:
        if char.isdigit():      #isdigit()判断数字的函数
            num_number+=1
        elif char.isalpha():    #isalpha()判断字符的函数
            char_number+=1
        elif char=="":          #""判断空格及其他
            space_number+=1
        else:
            other_number+=1
    print("数字个数:%d,字母个数:%d,空格个数:%d,其他字符:%d"%
(num_number,char_number,space_number,other_number))
    return
count("4 6as f65sa1f 56as56a as^S^%")
================= RESTART: D:\ing\python\python\files\eg2.py =================
数字个数:9,字母个数:12,空格个数:0,其他字符:7

17讲 06章 组合型数据简介和集合型数据学习

考纲

组合数据类型的基本概念
列表类型:定义、索引、切片
列表类型的操作:列表的操作函数,列表的操作方法
字典类型:定义、索引
字典类型的操作:字典的操作函数、字典的操作方法

组合数据类型的基本概念

集合类型:无序、唯一
序列类型:有先后顺序、不排他;字符串型、列表型
映射类型:键-值、key,value、字典型

集合型
>>> S={11,11,"11"}
>>> S
{'11', 11}      #集合的无序性、唯一性

交集&、并集|、差集-、补集^

集合类型

函数或方法描述
S.add(x)如果数据项x不在集合S中,将x增加到S
S.remove(x)如果x在集合S中,移除该元素;不在则产生KeyError异常
S.clear(x)移除S中所有数据项
len(S)返回集合S的元素个数
x in S如果x是S的元素,返回Ture;否则返回False
x not in S如果x不是S的元素,返回Ture;否则返回False
>>> s={12}
>>> type(s)
<class 'set'>
>>> s.add(47)
>>> s
{12, 47}
>>> s.remove(47)
>>> s
{12}
>>> s.clear()
>>> s
set()      #空
>>> s={12,"455","fdd"}
>>> len(s)
3
>>> 12 in s
True
>>> a={}
>>> type(a)
<class 'dict'>      #字典型
>>> a=set()
>>> type(a)
<class 'set'>      #集合型
>>> S=set("知之为知之不知为不知")
>>> S
{'不', '之', '知', '为'}
>>> for i in S:
	print(i,end="")

	
不之知为

18讲 列表型数据学习

序列型
>>> a=("12",23)
>>> type(a)
<class 'tuple'>
>>> a=("12",23,4)
>>> a
('12', 23, 4)
>>> a.add(14)
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    a.add(14)
AttributeError: 'tuple' object has no attribute 'add'
>>> a=set()
>>> a={"222",12}      #定义集合型数据
>>> a=("22",23)       #元组
>>> a=tuple()      #定义元组
>>> type(a)
<class 'tuple'>
>>> a=["5",454]
>>> type(a)
<class 'list'>
>>> a=list()
>>> type(a)
<class 'list'>

集合 { }
元组 ( )
列表 [ ]
字典 (键:值,键:值)

>>> a="sfegfds"
>>> type(a)
<class 'str'>
>>> a[2]
'e'
>>> a[2:4]
'eg'
>>> a[1:3:2]
'f'
>>> a[1:6:2]
'fgd'
>>> a=["df",["bg","bf"],45]
>>> type(a)
<class 'list'>
>>> a[1]
['bg', 'bf']
>>> a[0,2]
>>> a[0:2]
['df', ['bg', 'bf']]

>>> range(0,5,2)
range(0, 5, 2)

序列类型

操作符描述
x in s如果x是s的元素,返回Ture;否则返回False
x not in s如果x不是s的元素,返回Ture;否则返回False
s+t连接s和t
s* n 或 n* s将序列s复制n次
s[i]索引,返回序列的第i个元素
s[i:j]切片,返回包含序列s第i到j个元素的子序列(不包含第j个元素)
s[i:j:k]步骤切片,返回包含序列s第i到j个元素以k为步长的子序列
len(s)序列s的元素个数(长度)
min(s)元素s中的最小元素
max(s)元素s中的最大元素
s.index(x)序列s中第一次出现元素x的位置
s.count(x)序列s中出现x的总次数
>>> a=(12,52,78)
>>> max(a)
78
>>> s=["dd",12,"12"]
>>> s.index(12)
1
>>> s=["dd",12,"12",12]
>>> len(s)
4        #列表型数据有序可重复
>>> s
['dd', 12, '12', 12]
映射型
>>> a=(12,"34")
>>> type(a)
<class 'tuple'>
>>> a=(12)
>>> type(a)
<class 'int'>
>>> a=(12,)
>>> type(a)
<class 'tuple'>
>>> a=tuple()      #相当于空的
>>> a
()

Python语言在[]中表示区间需要使用冒号(😃,如切片;表示枚举使用逗号(,)如列表

列表型

操作函数描述
len(ls)列表ls的元素个数(长度)
min(ls)列表ls中的最小元素
max(ls)列表ls中的最大元素
list(ls)将x转变成列表类型
>>> list("Python")
['P', 'y', 't', 'h', 'o', 'n']
>>> list({"小明","小红","小白","小新"})
['小白', '小红', '小明', '小新']
>>> list({201801:"小明",201802:"小红",201803:"小白"})
[201801, 201802, 201803]

列表操作方法

方法描述
ls.append(x)在列表ls最后增加一个元素x
ls.insert(i,x)在列表ls第i位置增加元素x
ls.clear()删除ls中所有元素
ls.pop(i)将列表ls中第i项元素取出并从ls中删除该元素
ls.remove(x)将列表中出现的第一个元素x删除
ls.reverse()将列表ls中的元素反转
ls.copy()生成一个新列表,复制ls中所有元素
>>> a=["21","ad",55,55]
>>> a.append("god")      #增
>>> a
['21', 'ad', 55, 55, 'god']
>>> a.insert(3,"tod")      #插
>>> a
['21', 'ad', 55, 'tod', 55, 'god']
>>> a.pop(3)            #删
'tod'
>>> a
['21', 'ad', 55, 55, 'god']
>>> a.remove(55)      #移
>>> a
['21', 'ad', 55, 'god']
>>> a.reverse()          #反转
>>> a
['god', 55, 'ad', '21']
>>> a.clear()      #清
>>> a
[]
>>> type(a)
<class 'list'>
>>> a=[12,55]
>>> b=a
>>> a.clear()
>>> b
[]

【真题】

>>> list1=[i*2 for i in "Python"]
>>> print(list1)
['PP', 'yy', 'tt', 'hh', 'oo', 'nn']
>>> list1=[(m,n) for m in "AB" for n in "CD"]
>>> print(list1)
[('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D')]

19讲 字典型数据学习

{键值对}
>>> d={"201801":"小明","201802":"小红","201803":"小白"}
>>> print(d["201802"])
小红
>>> d["201802"]="小绿"
>>> print(d)
{'201802': '小绿', '201803': '小白', '201801': '小明'}
>>> a={"01":"张三","02":"李四"}
>>> type(a)
<class 'dict'>     #字典型
>>> a["02"]="李五"
>>> a
{'01': '张三', '02': '李五'}
>>> a.keys()
dict_keys(['01', '02'])
>>> a.values()
dict_values(['张三', '李五'])
>>> a.get("02")
'李五'
文本词频统计
# CalHamlet.py
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
hamletTxt = getText()
words  = hamletTxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))
=============== RESTART: F:\Python2\行文代码\行文代码\第6章\CalHamlet.py ===============
the        1138
and         965
to          754
of          669
you         550
a           542
i           542
my          514
hamlet      462
in          436

20讲 07章 文件的打开和关闭、读写

考纲

文件的使用:文件打开、关闭、读写
数据组织的维度:一维数据、二维数据
一维数据的处理:表示、存储、处理
二维数据的处理:表示、存储、处理
采用CSV格式对一二维数据文件的读写

文件的使用
f=open("a.txt","rt")    #r:读的方式,t:文本文件方式,txt:文件名
print(f.readline())     #读取第一行
f.close()               #关闭文件
>>> f1=open("D:\\ing\\python\\python\\files\\abcd.txt","rt")
>>> a=f1.readline()
>>> a
'新同学\n'
>>> print(f1.readline())
该起床了

>>> f.close()
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    f.close()
NameError: name 'f' is not defined
>>> print(f1.readline())

以二进制方式打开

#1
>>> f1=open("D:\\ing\\python\\python\\files\\abcd.txt","rb")
>>> print(f1.readline())
b'\xd0\xc2\xcd\xac\xd1\xa7\r\n'

#2
>>> p="D:\\ing\\python\\python\\files\\"
>>> p
'D:\\ing\\python\\python\\files\\'
>>> f=open(p+"abcd.txt","rb")
打开模式含义
‘r’只读模式,如果文件不存在,返回异常FileNotFoundError
‘w’覆盖写模式,文件不存在则创建,存在则完全覆盖源文件
‘x’创建写模式,文件不存在则创建,存在则返回异常FileExistsError
‘a’追加写模式,文件不存在则创建,存在则在源文件最后追加内容
‘b’二进制文件模式
‘t’文本文件模式,默认值
‘+’与r/w/x/a一同使用,在原功能基础上增加同时读写功能

w:将现有文件覆盖

>>> f=open("D:\\abcd.txt","wt")
>>> f.read()
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    f.read()
io.UnsupportedOperation: not readable
>>> f.close()
>>> f=open("D:\\abcd.txt","rt")
>>> f.read()
''

**read()😗*所有内容为字符串的形式进行读取
**readline()😗*把当前的内容以字符串的形式进行读取
**readlines()😗*把所有数据以每行为一个数据组成列表型数据

>>> f=open("D:\\abcd.txt","rt")
>>> a=f.read()  #把文件中所有的内容一次性读取
>>> f.close()
>>> p="D:\\"
>>> f=open(p+"abcd.txt","rt")
>>> print(f.readline())
onefewoa

>>> print(f.readline())
two dsjiog

>>> f.close()
>>> f=open(p+"abcd.txt","rt")
>>> print(f.read())
onefewoa
two dsjiog
three afno
fourfak;f
fivendasof

>>> b=f.readline()
>>> b
''
>>> f.close()
>>> f=open(p+"abcd.txt","rt")
>>> b=f.readlines()
>>> print(b)
['onefewoa\n', 'two dsjiog\n', 'three afno\n', 'fourfak;f\n', 'fivendasof\n']
>>> b
['onefewoa\n', 'two dsjiog\n', 'three afno\n', 'fourfak;f\n', 'fivendasof\n']
>>> type(b)
<class 'list'>

文件读取:"rt"

方法含义
f.read(size=-1)从文件中读入整个文件内容。参数可选,如果给出,读入前size长度的字符串或字节流
f.readline(size=-1)从文件中读入一行内容。参数可选,如果给出,读入该行前size长度的字符串或字节流
f.readlines(hint=-1)从文件中读入所有行,以还每行为元素形成一个列表。参数可选,如果给出,读入hint 行
f.seek(offset)改变当前文件操作指针的位置,offset 的值:0为文件开头;2为文件结尾
>>> f=open("D:\\abcd.txt","rt")
>>> f.read()
'onefewoa\ntwo dsjiog\nthree afno\nfourfak;f\nfivendasof\n'
>>> f.readline()
''
>>> f.seek(0)
0
>>> f.readline()
'onefewoa\n'
>>> f=open("D:\\abcd.txt","rt")
>>> for a in f:
	print(a)      #print()默认输出回车

	
onefewoa

two dsjiog

three afno

fourfak;f

fivendasof

>>> f.close()

文件写入"w、x、a"
w:改写
x:新建
a:追加

方法含义
f.write(s)向文件写入一个字符串或字节流
f.writelines(lines)将一个元素为字符串的列表整体写入文件
>>> f=open("D:\\abcd.txt","xt")
Traceback (most recent call last):
  File "<pyshell#115>", line 1, in <module>
    f=open("D:\\abcd.txt","xt")
FileExistsError: [Errno 17] File exists: 'D:\\abcd.txt'
#文件存在—进行报错
#文件不存在—进行创建
>>> f=open("D:\\abcd3.txt","xt")
#文件夹中创建"abc3.txt"文件(空文件)
>>> f=open("D:\\abcd3.txt","xt")
>>> f.write("abc")
3
>>> f.close()
>>> f=open("D:\\abcd3.txt","rt")
>>> f.read()
'abc'

>>> f=open("D:\\abcd3.txt","at")
>>> f.write("ab55c")
5
>>> f.read()
Traceback (most recent call last):
  File "<pyshell#128>", line 1, in <module>
    f.read()
io.UnsupportedOperation: not readable
>>> f=open("D:\\abcd3.txt","rt")
>>> f.read()
'abcab55c'

>>> xx=["ac","123"]
>>> type(xx)
<class 'list'>
>>> f.close()
>>> f=open("D:\\abcd3.txt","at")
>>> f.writelines(xx)
>>> f=open("D:\\abcd3.txt","rt")
>>> f.read()
'abcab55cac123'
>>> f.readlines()
[]
>>> f.seek(0)
0
>>> f.readlines()
['abcab55cac123']
# CalHamlet.py
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
hamletTxt = getText()
words  = hamletTxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))
=============== RESTART: F:\Python2\行文代码\行文代码\第6章\CalHamlet.py ===============
the        1138
and         965
to          754
of          669
you         550
a           542
i           542
my          514
hamlet      462
in          436

21讲 一维数据的处理

一维数据处理、数据分隔:空格、逗号、换行

join 将序列的元素以指定的符号连接成一个字符串

>>> p=["ab","112"]
>>> type(p)
<class 'list'>
>>> ",".join(p)
'ab,112'

>>> ",".join(p)
'ab,112'

>>> p2=["12","47"]
>>> type(",".join(p2))
<class 'str'>
>>> pp=["hello","world"]
>>> f=open("D:\\a.csv","w")
>>> f.read()
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    f.read()
io.UnsupportedOperation: not readable
>>> f=open("D:\\a.csv","w")
>>> f.write(",".join(pp)+"\n")
12
>>> f.close()

strip()将字符串前后的特定字符删除
join:列表转字符串
split:字符串转列表

>>> a="    abc   "
>>> a
'    abc   '
>>> a.strip("")
'    abc   '
>>> a.strip(" ")
'abc'
>>> 
>>> a="  a  bf  "
>>> a.strip(" ")
'a  bf'
>>> a="db   ge e34"
>>> a.split(" ")
['db', '', '', 'ge', 'e34']
>>> f=open("D:\\a.csv","r")
>>> pp=f.read()
>>> pp
'hello,world\n'
>>> pp=pp.strip("\n")
>>> pp
'hello,world'
>>> pp.split(",")
['hello', 'world']
>>> type(pp)
<class 'str'>
>>> pp=pp.split(",")
>>> type(pp)
<class 'list'>

22讲 二维数据的处理

>>> ls=[["学号","姓名"],["01","张三"],["02","李四"]]
>>> ls
[['学号', '姓名'], ['01', '张三'], ['02', '李四']]

>>> ls=[["学号","姓名"],["01","张三"],["02","李四"]]
>>> f=open("D:\\a.csv","w")
>>> for r in ls:
	f.write(",".join(r)+"\n")    #二维数据必须加回车"\n",否则是一维

	
6
6
6
>>> f.close()

>>> f=open("D:\\a.csv","r")
>>> f.read()
'学号,姓名\n01,张三\n02,李四\n'
>>> f.close()

>>> f=open("D:\\a.csv","r")
>>> ls=[]
>>> type(ls)
<class 'list'>
>>> ls={}
>>> type(ls)
<class 'dict'>
>>> ls=[]

#
>>> f.close()
>>> f=open("D:\\a.csv","r")
>>> ls=[]
>>> for l in f:
	ls.append(l.strip("\n").split(","))

	
>>> ls
[['学号', '姓名'], ['01', '张三'], ['02', '李四']]

#
>>> ls=[
        ["指标","2014年","2015年","2016年"],
	["居民消费价格指数","102","101.4","102"],
	["食品","103.1","102.3","104.6"],
	["烟酒及用品","99.4","102.1","101.5"],
	["衣着","102.4","102.7","101.4"],
	["家庭设备用品","101.2","101","100.5"],
    ]

>>> for row in ls:
	line=""
	for item in row:
		line +="{:10}\t".format(item)      #+=: 
	print(line)

	
指标        	2014年     	2015年     	2016年     	
居民消费价格指数  	102       	101.4     	102       	
食品        	103.1     	102.3     	104.6     	
烟酒及用品     	99.4      	102.1     	101.5     	
衣着        	102.4     	102.7     	101.4     	
家庭设备用品    	101.2     	101       	100.5     	


【案例】

# FinancePredict.py
def parseCSV(filename):
    dataNames, data = [], []
    f = open(filename, 'r', encoding='utf-8')
    for line in f:
        splitedLine = line.strip().split(',')
        if '指标' in splitedLine[0]:
            years = [int(x[:-1]) for x in splitedLine[1:]]
        else:
            dataNames.append('{:10}'.format(splitedLine[0]))
            data.append([float(x) for x in splitedLine[1:]])
    f.close()
    return years, dataNames, data
    
def means(data):
    return sum(data) / len(data)
    
def linearRegression(xlist, ylist):
    xmeans, ymeans = means(xlist), means(ylist)
    bNumerator = - len(xlist) * xmeans * ymeans
    bDenominator =  - len(xlist) * xmeans ** 2
    for x, y in zip(xlist, ylist):
        bNumerator += x * y
        bDenominator += x ** 2
    b = bNumerator / bDenominator
    a = ymeans - b * xmeans
    return a, b
    
def calNewData(newyears, a, b):
    return [(a + b * x) for x in newyears]
    
def showResults(years, dataNames, newDatas):
    print('{:^60}'.format('国家财政收支线性估计'))
    header = '指标       '
    for year in years:
        header += '{:10}'.format(year)
    print(header)
    for name, lineData in zip(dataNames, newDatas):
        line = name
        for data in lineData:
            line += '{:>10.1f}'.format(data)
        print(line)
    
def main():
    newyears = [x+2010 for x in range(7)]
    newDatas = []
    years, dataNames, datas = parseCSV('finance.csv')
    for data in datas:
        a, b = linearRegression(years, data)
        newDatas.append(calNewData(newyears, a, b))
    showResults(newyears, dataNames, newDatas)
    
main()

>>> 
============ RESTART: F:\Python2\行文代码\行文代码\第7章\FinancePredict.py ============
                         国家财政收支线性估计                         
指标             2010      2011      2012      2013      2014      2015      2016
全部收入        105359.6  114550.1  123740.6  132931.0  142121.5  151312.0  160502.4
中央收入         48169.1   52283.8   56398.5   60513.2   64627.9   68742.7   72857.4
地方收入         57190.6   62266.3   67342.1   72417.8   77493.6   82569.3   87645.1
全部支出        122936.9  133645.7  144354.5  155063.3  165772.1  176480.9  187189.8
中央支出         19037.5   20390.9   21744.3   23097.7   24451.1   25804.5   27157.9
地方支出        103899.4  113254.8  122610.2  131965.6  141321.0  150676.4  160031.9

23讲 08章 计算思维体育竞技编程

自顶向下
#求1到100之间的和
sum=0
for i in range(1,101):
    sum+=i
print(sum)

>>> 
=============== RESTART: D:\ing\python\python\files\example.py ===============
5050

(程序编写错误,待修改)

from random import random   #引用随机函数
def pi():
    print("这是一个小程序")
    print("解决比赛问题")

def get():
    A=eval(input("请输入A的能力值"))
    B=eval(input("请输入B的能力值"))
    N=eval(input("请输入比较的次数"))
    return A,B,N

def gO(SA,SB):
    return SA==15 or SB==15     #返回的是Ture,False

def OGame(A,B):
    SA,SB=0,0
    Qiu="A"
    while not gO(SA,SB):    #判断一下这单场比较是否结束,某方得分…
        if Qiu=="A":
            if random()<A:
                SA+=1
            else:
                Qiu="B"
        else:
            if random()<B:
                SB+=1
            else:
                Qiu="A"
    return SA,SB

def NGames(A,B,N):
    WA,WB=0,0       #WA,WB表示A,B两人得的总分
    for i in range(N):
        SA,SB==OGame(A,B)  #表示每场得分,OGame表示一场比较
        if SA>SB:
            WA+=1
        else:
            WB+=1
    return WA,WB

def po(WA,WB):
    N=WA+WB
    print("共比较了{}次".format(N))
    print("A赢了{}次,赢的概率是{:0.1%}".format(WA,WA/N))
    print("B赢了{}次,赢的概率是{:0.1%}".format(WB,WB/N))

def main():
    pi()            #输出程序的功能介绍
    A,B,N=get()     #用A表示A球员,B表示B球员,N表示次数
    WA,WB=NGames(A,B,N)  #获得AB赢的次数
    po(WA,WB)            #输出最终的比赛情况
main()

(程序编写错误,待修改)

#MatchAnalysis
from random import random
def printIntro():
    print("这个程序模拟两个选手A和B的某种竞技比赛")
    print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
def getInputs():
    a=eval(input("请输入选手A的能力值(0-1):"))
    b=eval(input("请输入选手B的能力值(0-1):"))
    n=eval(input("模拟比赛的次数:"))
    return a,b,n
def simNGames(n,probA,probB):
    winsA,winsB=0,0
    for i in range(n):
        scoreA,scoreB=simOneGame(porbA,porbB)
        if scoreA>scoreB:
            winsA +=1
        else:
            winsB +=1
    return winsA,winB
def gameOver(a,b):
    return a==15 or b==15
def simOneGame(probA,probB):
    scoreA,scoreB=0,0
    serving=="A"
    while not gameOver(scoreA,scoreB):
        if serving =="A":
            if random()<probA/(probA+probB):
                scoreA +=1
            else:
                serving="B"
        else:
            if random()<probB/(probA+probB):
                scoreB +=1
            else:
                serving="A"
    return scoreA,scoreB
def printSummary(winsA,winsB):
    n=winsA +winsB
    print("竞技分析开始,共模拟{}场比赛".format(n))
    print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA,winsA/n))
    print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB,winsB/n))
def main():
    printIntro()
    probA,probB,n=getInputs()
    winsA,winsB=simNGames(n,probA,probB)
    printSummary(winsA,winsB)
main()

24讲 Web页面元素提取

自底向上
1、函数的测试
>>> #更改默认工作路径
>>> import os
>>> os.getcwd()
'D:\\ing\\python\\python\\files'
>>> os.chdir("D:\\")
>>> os.getcwd()
'D:\\'

2、计算生态

常用的python内置函数


【实例】

(待修改)

def getHTMLlines(htmlpath):
    f = open(htmlpath, "r", encoding='utf-8')
    ls = f.readlines()
    f.close()
    return ls

def extractImageUrls(htmllist):
    urls = []
    for line in htmllist:
        if 'img' in line:
            url = line.split('src=')[-1].split('"')[1]
            if 'http' in url:
                urls.append(url)
    return urls


def main():
    inputfile  = 'nationalgeographic.html'
    outputfile = 'nationalgeographic-urls.txt'
    htmlLines = getHTMLlines(inputfile)
    imageUrls = extractImageUrls(htmlLines)
    showResults(imageUrls)
    saveResults(outputfile, imageUrls) 


main()

25讲 09章 turtle库

turtle库(必选)
random库(必选)
time库(可选)
>>> import turtle
>>> turtle.circle(200)
import turtle
turtle.pensize(4)
turtle.pencolor("yellow")
turtle.fillcolor("red")

turtle.begin_fill()
for i in range(5):
    turtle.forward(200)
    turtle.right(144)
turtle.end_fill()

26讲 random库

>>> from random import *
>>> random()
0.20497734458868722
>>> seed(10)
>>> random()
0.5714025946899135
>>> randint(7,12)
10
>>> randint(7,12)
10
>>> randint(7,12)
11
>>> 
>>> randint(7,12)
7
#编一个6位数的验证码,由数字;由数字和字母组成
import random
li1=[]
for i in range(6):
    num=random.randrange(0,10)
    li1.append(num)
print(li1)
=============== RESTART: D:\ing\python\python\files\example.py ===============
[1, 5, 4, 3, 4, 4]


    li1.append(str(num))
=============== RESTART: D:\ing\python\python\files\example.py ===============
['7', '8', '1', '1', '3', '6']


#编一个6位数的验证码,由数字;由数字和字母组成
import random
li1=[]
for i in range(6):
    num=random.randrange(0,10)
    li1.append(str(num))
s="".join(li1)
print(s)

=============== RESTART: D:\ing\python\python\files\example.py ===============
942274
#编一个6位数的验证码,由数字和字母组成
import random
li1=[]
for i in range(6):
    b=random.randrange(0,10)
    if b<5:
        num1=random.randrange(65,91)
        li1.append(chr(num1))
    else:
        num=random.randrange(0,10)
        li1.append(str(num))

s="".join(li1)
print(s)

=============== RESTART: D:\ing\python\python\files\example.py ===============
MK155O

27讲 time库

>>> import time
>>> time.time()
1582631472.4291966
>>> time.gmtime()
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=25, tm_hour=11, tm_min=52, tm_sec=18, tm_wday=1, tm_yday=56, tm_isdst=0)
>>> time.ctime()
'Tue Feb 25 19:54:02 2020'
import time
def coreLoop():
    limit=10**8
    while (limit > 0):
        limit -= 1

def otherLoop1():
    time.sleep(0.2)

def otherLoop2():
    time.sleep(0.4)

def main():
    startTime=time.localtime()
    print("程序开Y-%m-%d %H:%M:%S",startTime)
    staetPerfCounter = time.perf_counter()
    otherLoop1()
    otherLoop1PerfCounter=time.perf_counter()
    otherLoop1Perf=otherLoop1PerfCounter-staetPerfCounter
    coreLoop()
    coreLoopPerfCounter=time.perf_counter()
    coreLoopPerf=coreLoopPerfCounter-otherLoop1PerfCounter
    otherLoop2()
    otherLoop2PerfCounter=time.perf_counter()
    otherLoop2Perf=otherLoop2PerfCounter-coreLoopPerfCounter
    endPerfCounter=time.perf_counter()
    totalPerf=endPerfCounter-startPerfCounter
    endTime=time.localtime()
    print("模板1运行时间是:{}秒".format(otherLoop1Perf))
    print("核心模板运行时间是:{}秒".format(coreLoop1Perf))    
    print("模板2运行时间是:{}秒".format(otherLoop2Perf))
    print("程序运行总时间是:{}秒".format(totalPerf))
    print("程序结束时间:",time.strftime("Y-%m-%d %H:%M:%S",endTime))
main()

=============== RESTART: D:\ing\python\python\files\example.py ===============
程序开Y-%m-%d %H:%M:%S time.struct_time(tm_year=2020, tm_mon=2, tm_mday=25, tm_hour=21, tm_min=51, tm_sec=59, tm_wday=1, tm_yday=56, tm_isdst=0)

28讲 实例雪花

# SnowView.py
from turtle import *
from random import *
def drawSnow():
    hideturtle()
    pensize(2)
    for i in range(100):
        r, g, b = random(), random(), random()
        pencolor(r,g,b)
        penup()
        setx(randint(-350,350))
        sety(randint(1,270))
        pendown()
        dens = randint(8,12)
        snowsize = randint(10,14)
        for j in range(dens):
            forward(snowsize)
            backward(snowsize)
            right(360/dens)
def drawGround():
    hideturtle()
    for i in range(400):
        pensize(randint(5,10))
        x = randint(-400,350)
        y = randint(-280,-1)
        r, g, b = -y/280, -y/280, -y/280
        pencolor((r,g,b))
        penup()
        goto(x,y)
        pendown()
        forward(randint(40,100))
setup(800,600,200,200)
tracer(False)
bgcolor("black")
drawSnow()
drawGround()
done()

29讲 10章 PIP,PyInstaller和jieba库

考纲

第三方库的获取和安装
脚本程序转变为可执行程序的第三方库:PyInstaller(必选)
第三方库:jieba库(必选)
第三方库:wordcloud库(可选)

C:\Users\asus>F:
F:\Python2\行文代码\第9章>PyInstaller -F SnowView.py
.
.
.

(错误)

F:\Python2\行文代码\第9章>PyInstaller -i snowflake.ico -F SnowView.py
>>> a="我是中国人我爱中国"
>>> import jieba
>>> jieba.lcut(a)
['我', '是', '中国', '人', '我', '爱', '中国']

>>> jieba.lcut("全国计算机等级考试")
['全国', '计算机', '等级', '考试']

>>> jieba.lcut("全国计算机等级考试",cut_all=True)
['全国', '国计', '计算', '计算机', '算机', '等级', '考试']
词云
from wordcloud import WordCloud
t="i like python i am learning python"
word=WordCloud().generate(t)
word.to_file("aaa.png")

字体文件夹 C:\Windows\Fonts

import jieba
from wordcloud import WordCloud
txt="程序将设计语言是计算机能够理解和识别用户操作意图的一种交互体系,它按照特定规划组织、计算机指令,使计算机能够自动进行各种运算处理。"

words=jieba.lcut(txt)

newtxt=" ".join(words)

wordcloud=WordCloud(font_path="msyh.ttc").generate(newtxt)

wordcloud.to_file("词云中文例子图.png")

pip install scipy

from wordcloud import WordCloud
from scipy.misc import imread
mask=imread("AliceMask.png")
f=open("AliceInWonderland.txt","r",ending="utf-8")
txt=f.read()
wordcloud=WordCloud(backgroud_color="white",\
                    width=800,\
                    height=600,\
                    max_words=200,\
                    max_font_size=80,\
                    mask=mask,\
                    ).generate(txt)
wordcloud.to_file("AliceInWonderland.png")
PyInstaller
C:\Users\asus>F:
F:\Python2\行文代码\第9章>PyInstaller -F SnowView.py
.
.
.

(错误)

F:\Python2\行文代码\第9章>PyInstaller -i snowflake.ico -F SnowView.py
C:\Users\asus>pip download PyInstaller
Collecting PyInstaller
  File was already downloaded c:\users\asus\PyInstaller-3.6.tar.gz
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Collecting setuptools
  File was already downloaded c:\users\asus\setuptools-45.2.0-py3-none-any.whl
Collecting pefile>=2017.8.1
  File was already downloaded c:\users\asus\pefile-2019.4.18.tar.gz
Collecting altgraph
  File was already downloaded c:\users\asus\altgraph-0.17-py2.py3-none-any.whl
Collecting pywin32-ctypes>=0.2.0
  File was already downloaded c:\users\asus\pywin32_ctypes-0.2.0-py2.py3-none-any.whl
Collecting future
  Downloading future-0.18.2.tar.gz (829 kB)
     |████████████████████████████████| 829 kB 11 kB/s
  Saved c:\users\asus\future-0.18.2.tar.gz
Successfully downloaded PyInstaller setuptools pefile altgraph pywin32-ctypes future
C:\Users\asus>pip install PyInstaller
Collecting PyInstaller
  Using cached PyInstaller-3.6.tar.gz (3.5 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Requirement already satisfied: pefile>=2017.8.1 in d:\python35\lib\site-packages (from PyInstaller) (2018.8.8)
Requirement already satisfied: setuptools in d:\python35\lib\site-packages (from PyInstaller) (28.8.0)
Collecting pywin32-ctypes>=0.2.0
  Using cached pywin32_ctypes-0.2.0-py2.py3-none-any.whl (28 kB)
Collecting altgraph
  Using cached altgraph-0.17-py2.py3-none-any.whl (21 kB)
Requirement already satisfied: future in d:\python35\lib\site-packages (from pefile>=2017.8.1->PyInstaller) (0.16.0)
Building wheels for collected packages: PyInstaller
  Building wheel for PyInstaller (PEP 517) ... done
  Created wheel for PyInstaller: filename=PyInstaller-3.6-py3-none-any.whl size=2926582 sha256=d2b88997d4ea077b1c865b11852ec71148da4f8eaf9474803526d5537ebde0f5
  Stored in directory: c:\users\asus\appdata\local\pip\cache\wheels\dd\b6\1e\537449aa2dd036db5da60b14c61f136c5a9e16d79bd5491fc6
Successfully built PyInstaller
Installing collected packages: pywin32-ctypes, altgraph, PyInstaller
Successfully installed PyInstaller-3.6 altgraph-0.17 pywin32-ctypes-0.2.0
pip
Microsoft Windows [版本 10.0.17763.1039]
(c) 2018 Microsoft Corporation。保留所有权利。

C:\Users\asus>python
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello")
hello
>>> exit()

C:\Users\asus>pip install pygame
Collecting pygame
  Downloading https://files.pythonhosted.org/packages/45/a5/580578790aa2f8f274855d45b4c89ffb910f1c72ddb754873b2ae8d7fc7f/pygame-1.9.6-cp35-cp35m-win_amd64.whl (4.3MB)
    100% |████████████████████████████████| 4.3MB 13kB/s
Installing collected packages: pygame
Successfully installed pygame-1.9.6
You are using pip version 9.0.1, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\asus>pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
pip (9.0.1)
pygame (1.9.6)
setuptools (28.8.0)
You are using pip version 9.0.1, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\asus>pip wordcloud
ERROR: unknown command "wordcloud"

C:\Users\asus>python --version
Python 3.5.3

C:\Users\asus>pip unistall wordcloud
ERROR: unknown command "unistall" - maybe you meant "uninstall"

C:\Users\asus>pip install wordcloud
Collecting wordcloud
  Downloading https://files.pythonhosted.org/packages/d2/11/ebc51ff21ebc1a48b040859b0062bff4aa297c6cf26b1aa08a2c0ce22668/wordcloud-1.6.0-cp35-cp35m-win_amd64.whl (153kB)
    100% |████████████████████████████████| 163kB 6.5kB/s
Collecting numpy>=1.6.1 (from wordcloud)
  Could not find a version that satisfies the requirement numpy>=1.6.1 (from wordcloud) (from versions: )
No matching distribution found for numpy>=1.6.1 (from wordcloud)
You are using pip version 9.0.1, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\asus>pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
pip (9.0.1)
pygame (1.9.6)
setuptools (28.8.0)
You are using pip version 9.0.1, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\asus>pip help

Usage:
  pip <command> [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  search                      Search PyPI for packages.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring
                              environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be
                              used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be
                              used up to 3 times (corresponding to WARNING,
                              ERROR, and CRITICAL logging levels).
  --log <path>                Path to a verbose appending log.
  --proxy <proxy>             Specify a proxy in the form
                              [user:passwd@]proxy.server:port.
  --retries <retries>         Maximum number of retries each connection should
                              attempt (default 5 times).
  --timeout <sec>             Set the socket timeout (default 15 seconds).
  --exists-action <action>    Default action when a path already exists:
                              (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host <hostname>   Mark this host as trusted, even though it does
                              not have valid or any HTTPS.
  --cert <path>               Path to alternate CA bundle.
  --client-cert <path>        Path to SSL client certificate, a single file
                              containing the private key and the certificate
                              in PEM format.
  --cache-dir <dir>           Store the cache data in <dir>.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine
                              whether a new version of pip is available for
                              download. Implied with --no-index.

C:\Users\asus>

30讲 jieba库和词云库的实例

>>> d={"ab":3,"fe":78,"ds":34}
>>> d
{'ds': 34, 'ab': 3, 'fe': 78}
>>> d.get("ds")
34
>>> d.get("ds",0)
34
>>> d.get("ds",3)
34
>>> d.get("ds2",0)
0
>>> list(d)
['ds', 'ab', 'fe']
>>> list(d.item())
>>> list(d.items())
[('ds', 34), ('ab', 3), ('fe', 78)]
  • 1
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值