一、Python语言的特点(优点)
1、简单易用,支持在macOS、Windows、Unix等操作系统适用
2、编程语言,大量的数据结构、支持开发大型程序
3、错误检查很多
4、高级语言,内置灵活数组和字典,更通用的数据类型
5、模块化,便于复用
6、内置大量标准模块(包括 I/O、系统调用、套接字,甚至还包括 Tk 图形用户界面工作套件。)
7、解释型语言,无需编译和链接,节约开发时间
8、解释器支持交互式操作
9、超好用的计算器
10、简洁、易懂、代码短
11、可扩展
 
二、Python解释器
1、调用解释器
默认安装路径:
/usr/local/bin/python3.9

建立软链接使得输入python时找到安装的新版本

ln -f /usr/local/bin/python3.9 /usr/local/bin/python

传入参数:解释器读取命令行参数,把脚本名与其他参数转化为字符串列表存到 sys 模块的 argv 变量里。

交互模式:主提示符,提示输入下一条指令,主提示符通常用三个大于号(>>>)表示;输入连续行时,显示次要提示符,默认是三个点(...)。
2、解释器的运行环境
声明文件的编码,文件的第一行要写成特殊注释。句法如下:
# -*- coding: encoding -*- 
# -*- coding: uft-8 -*-

 

三、快速入门
1、数字
(1)支持 加+ 减- 乘* 除/ 取整// 取余% 乘方**
(2)除法运算返回结果为浮点数
(3)混合运算中包含浮点数,则结果为浮点数
(4)交互模式下,上次输出的表达式会赋给变量 _
 1 D:\>python
 2 Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
 3 Type "help", "copyright", "credits" or "license" for more information.
 4 >>> 1+1 // 5 2
 6 >>> 5-2 // 7 3
 8 >>> 2*4 // 9 8
10 >>> 2/4 //11 0.5
12 >>> 2//4 // 除法取整
13 0
14 >>> 17%4 // 取余
15 1
16 >>> 4**3 // 乘方
17 64
18 >>> 4+1.0 //混合类型运算
19 5.0
20 >>> 1+_ // 交互模式下,上次输出的表达式会赋给变量 _
21 6.0
22 >>>
加减乘除

 

2、字符串

(1)转义字符
 1 >>> 'I\'m a teacher' // 反斜杠 \ 用于转义
 2 "I'm a teacher"
 3 >>> "I'm a teacher"
 4 "I'm a teacher"
 5 >>> 'I'm a teacher'
 6   File "<stdin>", line 1
 7     'I'm a teacher'
 8        ^
 9 SyntaxError: invalid syntax
10 >>> 'C:\usr\local\bin'
11   File "<stdin>", line 1
12     'C:\usr\local\bin'
13                       ^
14 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape
15 >>> r'C:\usr\local\bin' // 不希望前置 \ 的字符转义成特殊字符,可使用原始字符串,在引号前添加 r 即可
16 'C:\\usr\\local\\bin'

(2)注意

 1 >>> text = ('Put several strings within parentheses '
 2 ...  'to have them joined together.')
 3 >>> text 
 4 'Put several strings within parentheses to have them joined together.'
 5 >>> 'py''thon' // 两个字面值合并
 6 'python'
 7 >>> a = "Py"
 8 >>> a + "thon" // + 拼接
 9 'Python'
10 >>> a 'thon'
11   File "<stdin>", line 1
12     a 'thon'
13       ^
14 SyntaxError: invalid syntax
15 >>> a = "python"
16 >>> a[0] // 索引从0开始
17 'p'
18 >>> a[-2]
19 'o'
20 >>> a[:] // 切片,省略开始索引即0、省略结束索引即-1
21 'python'
22 >>> a[:2] 
23 'py'
24 >>> a[1:2] // 左包含右不包含
25 'y'
26 >>> a[8] // 索引越界报错
27 Traceback (most recent call last):
28   File "<stdin>", line 1, in <module>
29 IndexError: string index out of range
30 >>> a[2:8] // 切片越界自动处理
31 'thon'
32 >>> len(a) //len字符串长度
33 6
34 >>>
35 >>> a = "python"
36 >>> a[0]="P" // 字符串不能修改
37 Traceback (most recent call last):
38   File "<stdin>", line 1, in <module>
39 TypeError: 'str' object does not support item assignment
View Code

(3)实践

 1 name = "congcong"
 2 item = "My name is {names}, I am {years} old"
 3 
 4 print(name.capitalize()) # 首字母大写
 5 print(name.count("c")) # 统计字母个数
 6 print(name.center(50, "-")) # 50个字符,不够的用-补充完整且居中,---------------------congcong---------------------
 7 print(name.encode()) # 编码
 8 print(name.endswith("g")) # 判断是否以xx结尾,是的话返回True
 9 print(name.expandtabs(tabsize=20)) # 将\t即tab键转成多少个空格,# name = "cong\tcong"
10 print(name.find("g")) # 找到字母的索引
11 print(item.format(names=name, years=27))
12 print(item.format_map({"names":name, "years":27}))
13 print(item.isalnum()) # 判断是否英文字符+1234567890
14 print("23ab".isalnum())
15 print("Cc".isalpha()) # 判断是否英文字符
16 print("12".isdecimal()) # 判断是否十进制
17 print("1A".isdecimal())
18 print(name.isdigit()) # 判断是否数字
19 print("ab".isidentifier()) # 判断是否一个合法的标识符/变量名,即是否符合变量名的命名规则
20 print(name.islower()) # 判断是否小写
21 print("123".isnumeric()) # 判断是否只有数字
22 print(" ".isspace()) # 判断是否空格
23 print("My Name".istitle()) # 判断是否每个单词以大写字母开头
24 print(name.isprintable()) # 判断是否可以打印,tty file和drive file不支持打印
25 print("ABC".isupper()) # 判断是否大写
26 print("+".join(["1", "2", "3"])) # 用x连接
27 print(name.ljust(50, "*")) # 50个字符,不够的用*补充完整,原字符串在左侧
28 print(name.rjust(50, "*")) # 50个字符,不够的用*补充完整,原字符串在右侧
29 print("Abc".lower()) # 所有变小写
30 print(name.upper()) # 所有变大写
31 print("\n ----abc----".lstrip()) # 左侧去掉空格和回车
32 print("----abc---- \n".rstrip()) # 右侧去掉空格和回车
33 print("   abc  \n".strip()) # 去掉首尾的空格和回车
34 p = str.maketrans("cong", "1234") # 对应
35 print(name.translate(p)) # 转换
36 print("congcong".replace("c", "C")) # 将c替换成C
37 print("congcong".replace("c", "C", 1)) # 将第1个c替换成C
38 print("congcong".rfind("c")) # 找到最右边的c的索引,即找到最后一个c的索引
39 print("cong cong".split()) # 将字符串以空格分割成列表
40 print("1+2+3+4".split("+")) # 以+分割
41 print("1+2\n+3+4".splitlines()) # 自动识别不同系统的换行符,且以换行符分割
42 print("Ab从D".swapcase()) # 将大写字母<->小写字母;aB从d
43 print("cong cong".title()) # 将每个字符转换为title格式;Cong Cong
44 print("cc".zfill(5)) # 5个字符,不够的用0补齐
45 
46 # 打印结果
47 Congcong
48 2
49 ---------------------congcong---------------------
50 b'congcong'
51 True
52 congcong
53 3
54 My name is congcong, I am 27 old
55 My name is congcong, I am 27 old
56 False
57 True
58 True
59 True
60 False
61 False
62 True
63 True
64 True
65 True
66 True
67 True
68 True
69 1+2+3
70 congcong******************************************
71 ******************************************congcong
72 abc
73 CONGCONG
74 ----abc----
75 ----abc----
76 abc
77 12341234
78 CongCong
79 Congcong
80 4
81 ['cong', 'cong']
82 ['1', '2', '3', '4']
83 ['1+2', '+3+4']
84 aB从d
85 Cong Cong
86 000cc
View Code

 

3、列表实践:可嵌套列表、字典,可嵌套多层
 1 # 列表
 2 names = []
 3 print(names)
 4 
 5 names = ["4Changxiangen", "#!Zhengna", "cSonghaomiao", "Guocongcong"]
 6 print(names)
 7 print(names[0])
 8 print(names[1], names[2])
 9 
10 # 顾头不顾尾,左闭右开;
11 # 切片,把一部分数据从列表中切下来
12 print(names[1:3])
13 
14 # 跳着切片
15 print("*************")
16 print(names)
17 print(names[0:-1:2])
18 print(names[::2])
19 print(names[:])
20 
21 # 取最后一个值
22 print(names[3])
23 print(names[-1])
24 
25 # 取最后两个值
26 print("**********1*********")
27 print(names[-1:-3]) # 为空,切片只能从左到右
28 print(names[-3:-1]) # 错误
29 print(names[-2:]) # 正确
30 
31 # 取前2个值
32 print("**********2*********")
33 print(names[:2])
34 
35 # 追加,放在最后面
36 names.append("Xingjing")
37 print(names)
38 
39 # 插入第2个位置,"1"是下标
40 names.insert(1, "Xiaoguo")
41 print(names)
42 
43 # 插入第4个位置
44 # names.insert(3, "XiaoCong")
45 # print(names)
46 
47 # 修改,即重新赋值
48 # names[3] = "Congcong"
49 # print(names)
50 
51 # 删除"Xiaoguo"
52 # names.remove("Xiaoguo")
53 # del names[1]
54 # names.pop()
55 # names.pop(1)
56 print(names)
57 
58 # 找某人的位置
59 # print(names.index("Congcong"))
60 # print(names[names.index("Congcong")])
61 
62 # 统计"Congcong"的个数
63 names.insert(3, "Congcong")
64 print(names.count("Congcong"))
65 print(names)
66 
67 # 反转
68 names.reverse()
69 print(names)
70 
71 # 排序
72 # 特殊字符、数字、大写字母、小写字母
73 # ASCII码
74 names.sort()
75 print(names)
76 
77 # 清空
78 # names.clear()
79 # print(names)
80 
81 # 扩展
82 names1 = [1, 2, 3]
83 names.extend(names1)
84 print(names, names1)
85 del names1
86 print(names)
87 
88 # 循环
89 for i in names:
90     print(i)
View Code

 

四、流程控制语句
 
# 质数
# range()左包含右不包含
# 循环的 else 子句则在未运行 break 时执行
# break 跳出整个循环
for n in range(2, 20):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')
质数
1 # 奇数、偶数
2 # continue 跳出本次循环,继续下一次循环
3 for i in range(2, 10):
4     if i % 2 == 0:
5         print(f"{i} is even number")
6         continue
7     print(f"{i} is odd number")
奇数、偶数

 

五、面向对象重要概念
类:关键字class
方法名:关键字def
方法与函数的区别:方法在类中,函数在类外
静态属性:类变量,在类之中,方法之外定义
动态方法:类中的def方法
实例变量:类之中,方法之内,以 self.变量名 方式定义
普通变量:在类之中,方法之中,并且前面没有 self. 开头
实例化:变量 = 类名()
通过实例对象调用类属性
通过类直接调用属性
构造方法:在类实例化的时候自动执行
 1 # -*- coding: utf-8 -*-
 2 # @Author : self
 3 # @File : house.py
 4 '''
 5 class 类名:
 6     多个类属性...
 7     多个类方法...
 8 '''
 9 
10 class House:
11     # 静态属性 -> 类变量,在类之中,方法之外定义
12     door = "red"
13     floor = "white"
14 
15     # 构造方法,在类实例化的时候自动执行
16     def __init__(self):
17         # 加上 self. 变成实例变量
18         print(self.door)
19         # 定义实例变量 -> 类之中,方法之内,以 self.变量名 方式定义
20         # 实例变量的作用域是整个类中的所有方法
21         self.kitchen = "cook"
22 
23     # 动态方法
24     def sleep(self):
25         # 普通变量 -> 在类之中,方法之中,并且前面没有 self. 开头
26         bed = "席梦思"
27         print(f"在房子里可以躺在{bed}睡觉")
28 
29     def cook(self):
30         print("在房子里可以做饭吃")
31 
32 
33 if __name__ == '__main__':
34     # 实例化 -> 变量 = 类()
35     north_house = House()
36     china_house = House()
37 
38     north_house.sleep()
39 
40     # 通过类直接修改属性
41     House.door = "green"
42     
43     # 通过实例修改属性
44     north_house.door = "white"
45     
46     # 通过实例对象调用类属性
47     print(north_house.door)
48     print(china_house.door)
49     
50     # 通过类也可以调用属性
51     print(House.door)
 1 # -*- coding: utf-8 -*-
 2 # @Author : feier
 3 # @File : houyi.py
 4 from python_pratice.python_oop.game_oop import Game
 5 # 快速导包:Alt + enter
 6 '''
 7 后裔,后裔继承了 Game 的 hp 和 power。并多了护甲属性。
 8 重新定义另外一个 defense 属性:
 9 final_hp = hp + defense - enemy_power
10 enemy_final_hp = enemy_hp - power
11 两个 hp 进行对比,血量先为零的人输掉比赛
12 '''
13 
14 # 类名 驼峰式
15 class HouYi(Game):
16 
17     def __init__(self, my_hp, enemy_hp):
18         self.defense = 100
19         # 继承父类的构造方法
20         super().__init__(my_hp, enemy_hp)
21 
22     def fight(self):
23         # 改造一下 my_hp 的计算方式
24         while True:
25             # 我的剩余血量
26             self.my_hp = self.my_hp + self.defense - self.enemy_power
27             # 敌人的剩余血量
28             self.enemy_hp -= self.my_power
29             print(f"我的血量:{self.my_hp} VS 敌人血量:{self.enemy_hp}")
30             # self.rest(3)
31             # 胜负判断
32             if self.my_hp <= 0:
33                 print("我输了")
34                 break
35             elif self.enemy_hp <= 0:
36                 print("我赢了")
37                 break
38         super().__private_method()
39 
40 
41 if __name__ == '__main__':
42     # 定义形参,传实参
43     houyi = HouYi(1000, 1100)
44     # 子类对象可以直接调用父类的属性和方法
45     print(houyi.my_power)
46     houyi.fight()
47     # houyi.rest(3)
48     # 演示命令行上传
继承
 1 # -*- coding: utf-8 -*-
 2 # @Author : feier
 3 # @File : log_decorator.py
 4 import logging
 5 
 6 # 设置基本配置
 7 logging.basicConfig(level=logging.DEBUG)
 8 # 自定义 logger
 9 logger = logging.getLogger('log')
10 
11 # func(a,b,c)
12 
13 # 定义装饰器
14 def log_decorator(func):
15     '''
16     给传入的函数添加日志信息
17     :param func: 传入的函数
18     :return: 添加了log信息的函数
19     '''
20     def wrapper(*args, **kwargs):
21         # 加上 log 信息
22         logger.debug(f"装饰器:{log_decorator.__name__} -> 传入函数:{func.__name__}")
23         # 调用传入的函数对象
24         return func(*args, **kwargs)
25     return wrapper
装饰器

 

参考:

https://github.com/ceshiren/HogwartsLG6(拉勾教育)

posted on 2021-01-26 15:36  guoccf  阅读(116)  评论(0编辑  收藏  举报