开篇介绍
运维/网络为什么要学习编程?
- 所有已学的命令其实都是已经编制好的程序
- 在云计算领域当中,繁琐的命令配置已经不能够在满足日常需求,需要贴近业务/研发
- 在网络安全领域当中,可以深入理解渗透、攻防等细节,Kali-Linux,SDN夯实基础
- 对于校招的学生而言,大型互联网公司,笔试题必考编程题
为什么要学习Python?
- Shell是Linux自带的编程语言,语法晦涩难懂,额外的扩展功能比较少,效率比较高
- C/C++/Java入门门槛比较高,纯开发语言,不要适合运维的需求(快速,简单,明了)
- Python属于解释型语言,俗称脚本,综合应用能力很强,开源+社区人员多,客户端、后台/后端/服务端、爬虫、嵌入式、自动化运维、网络安全、人工智能
本次课程目标
- 12天掌握Python常用知识
- 学习用编程思维去解决一些实际的计算问题
- 针对校招,LeetCode+牛客网算题锻炼
推荐书籍
- 《Python语言程序设计》 主要教材
- 《Python基础教程 第三版》字典
- 《Python学习手册 第四版》字典
Python环境搭建
- Linux下RedHat/CentOS 自带Python2.x,本次课程需要用Python3.x
- Windows安装Python3包
- 命令行运行方式,快速方便,不易保存
- 脚本文件运行方式,容易保存,操作较麻烦
- Python源代码文件编辑软件:VIM、VSCode、PyCharm
- MarkDownPad格式编辑软件,Typora
学习建议
- Python概念性的东西稍微少一点的,但不不好理解
- 多敲!多敲!多敲!量变产生质变
- 能别旷课请假就别,很强连贯性的
上课须知
- 有事请假找班主任审批假条(线上的远程假条),逾期不候;无故缺勤视为
旷课
- 作业在规定时间内提交,逾期不候;作业没完成视为
旷课
- 两次
迟到
,视为旷课
旷课
两次,直接踢群,不予复听;
第一章 语法基础
软件的定义
是指一系列按照特定顺序组织的计算机数据与指令的集合
数据:计算机所能够识别的一些数据,硬盘当中:avi,doc,txt,py,内存当中:常量、变量、函数、对象、类
指令:操作这些数据进行先关计算的步骤
软件的运行流程
由Python写出的代码叫做源代码,源代码是否能够直接被计算机识别?将源代码编译成计算机所能够识别的机器码,然后计算机执行机器码即可
软件的两种操作方式:
- 图形化界面操作方式
- 命令行操作方式
高级编程语言分为两类:
- 静态编译型:C、C++、Java
- 编译:必须将源代码完全编译成机器码文件,再去执行机器码文件,运行程序
- 静态:变量必须有明确的数据类型定义
- 动态解释型:Python、JavaScript、Mathlab、Ruby、Go
- 解释:没有必要将代码完全必成机器码,读取一句源码-编译一句-运行一句
- 动态:变量没有明确的数据类型定义,任何数据类型变量都可以存
1.1 基本数据
整数 int
通常被称为整型,是零、正数和负数,不带小数点
表示数字的时候,我们也可以使用进制的形式 二 八 十 十六
>>> print(10)
10
>>> print(1001)
1001
>>> print(0b1001)#把二进制1001,输出十进制
9
>>> print(0o1234)#把八进制1234,输出十进制
668
>>> print(0x9C1A)#把十六进制9C1A,输出十进制
39962
>>> print(0x9W2Y)
File "<stdin>", line 1
print(0x9W2Y)
^
SyntaxError: invalid syntax
注意:打印的结果一律为十进制
Python的整数长度为32位-4字节,并且通常是连续分配内存空间 id()函数
>>> id(0)
2034812832
>>> id(1)
2034812848
>>> id(2)
2034812864
Python在初始化环境的时候就在内存里划分出一块空间,专门用于整数对象的存取。当然,这块空间也不是无限大的,能保存的数据是有限的
>>> id(251)
2034816848
>>> id(260)
13647712
>>> id(-10)
13647696
小整数对象池
Python初始化的时候会自动创建一个小整数对象池,方便我们调用,避免后期重复生成
这里面只包含-5~256,这些数字是我们最常用的数字,所以就预先被Python加载进内存
对于整数的使用而言,不在-5~256之间,一律重新创建
>>> id(-5)
2034812752
>>> id(-6)
13647728
>>> id(256)
2034816928
>>> id(257)
13647648
>>> id(300)
13647696
>>> id(300)
13647712
>>> id(300)
13647680
浮点型 float
浮点数也就是小数,如果小数过于长,也可以用科学计数法表示
>>> print(3.14)
3.14
>>> print(1.298765e10)
12987650000.0
>>> print(0.89e-5)
8.9e-06
>>> print(1.23e-8)
1.23e-08
复数 complex
复数由实部和虚部组成,a+bj
>>> print(1+2)
3
>>> print(1+2j)
(1+2j)
>>> (1+2j)*(1-2j)
(5+0j)
>>> complex(1,2)*complex(1,-2)
(5+0j)
布尔型 bool
对与错、0和1,正与反,都是传统意义上的布尔类型
在Python里面,布尔类型只有两个 True,False
布尔类型只能在逻辑运算和比较运算中存在
>>> True + False
1
>>> True - False
1
>>> 3 > 2
True
>>> 2 < 1
False
>>> 3 > 2 and 2 < 1
False
None空值 NoneType
空值不能理解为数字0,空集φ;我们主要用在创建序列,和面向对象编程中使用
>>> None + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> [None] * 10 # 创建一个长度为10的列表 没有数据 但有空间
[None, None, None, None, None, None, None, None, None, None]
字符串 str
字符串有三种表现形式,单引号,双引号,三引号(一般用在注释)
>>> print("HelloWorld")
HelloWorld
>>> print('你好')
你好
>>> print(" '' ")
''
>>> print(' "" ')
""
>>> print(' ' ')
File "<stdin>", line 1
print(' ' ')
^
SyntaxError: EOL while scanning string literal
>>> print(' \' ')
'
转义符
\\
:反斜杠\'
:单引号\"
:双引号\n
:换行\t
:横向制表符
>>> print(' \' ')
'
>>> print("\")
File "<stdin>", line 1
print("\")
^
SyntaxError: EOL while scanning string literal
>>> print("\\")
\
变量
变量:在程序运行过程中,值会发生改变的量
常量:在程序运行过程中,值不会发生改变的量 (字面量,直接在代码中出现的数据)
无论是变量还是常量,在创建时都会在内存中开辟一个空间,用于保存它们的值
# Java中基本数据类型变量a,b 和 引用数据类型变量c d e
int a = 3;
int b = 8;
Object c = new Object();
Object d = new Object();
Object e = c;
在Python当中,一律皆对象
>>> a = 1
>>> b = 1
>>> c = 1
>>> a == b
True
>>> id(1)
2034812848
>>> id(a)
2034812848
>>> id(b)
2034812848
>>> d = a
>>> d == b
True
>>> num1 = 300
>>> num2 = 300
>>> num3 = 300
>>> id(num1)
13647712
>>> id(num2)
13647696
>>> id(num3)
13647680
>>> num1 == num2
True
==不能一味的去比地址,还要比两个对象的内容是否相等
变量这个空间中,只能存某个数据对象的地址,变量就是该对象的一个引用而已
变量必须在赋值后在能被调用
>>> print(num4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'num4' is not defined
变量可以连续赋值
>>> a=b=c=10
>>> a
10
>>> b
10
>>> c
10
>>> a,b,c =10,20,30
>>> a
10
>>> b
20
>>> c
30
>>> a=b=c=1000
>>> id(a)
13647776
>>> id(b)
13647776
>>> id(c)
13647776
>>> a=1000
>>> b=1000
>>> c=1000
>>> id(a)
13647792
>>> id(b)
13647648
>>> id(c)
13647824
Python中变量本身是没有数据类型约束的,它只是一个对象的引用,存的是对象数据的内存地址
只有数据对象之间有数据类型的区分
标识符
所谓的标识符就是我们对变量、常量、函数、类等起的名称
如下规定:
- 第一个字符必须是字母或者下划线
_
- 虽然Python支持中文,我们也可以使用中文来命名,但是我们不推荐
- 以下划线开头的话,在面向对象编程当中,有特殊含义-私有
- 标识符的其他的部分由字母、数字、下划线组成
- 标识符对字母大小写敏感
- 变量名全部小写,常量名全部大写(Python当中不存在常量PI = 3.14,本质还是一个变量)
- 函数名用小写加下划线方式,等同于变量名
- 类名用大驼峰式命名方法:如果名称由多个单词组成,则每个单词首字母大写
变量的命名不要使用关键字和内置函数的名称!
>>> True = 2
File "<stdin>", line 1
SyntaxError: cannot assign to True
>>> if = 3
File "<stdin>", line 1
if = 3
^
SyntaxError: invalid syntax
关键字
指的是已经被高级编程语言赋予特殊含义的单词
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
同样也不能使用内置函数(将内置函数的名称 改变为了别的用途)
>>> id(2)
2034812864
>>> id = 3
>>> id + 1
4
>>> id(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Python中,一切皆对象,函数本身也是对象!
>>> id(2)
2034812864
>>> id(id)
45545184
>>> abc = id
>>> abc(1)
2034812848
>>> id(1)
2034812848
>>> id = 10
>>> print(id)
10
>>> abc(id)
2034812992
一共有多少内置函数
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
注释
注解说明程序使用的一段文本信息,不算是程序的一部分
- 单行注释:# 注释内容
- 多行注释:多个单行注释
- 文档注释:""“注释内容 可以说明类信息 函数信息”""
1.2 内置函数
print函数
输出函数,将内容格式化的去显示在控制台窗口
>>> a=1
>>> b=2
>>> c=3
>>> print(abc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
>>> print(a,b,c)
1 2 3
print函数原型:print(self, *args ,sep=' ',end='\n',file=None)
-
self:先不管
-
*args:arguments,多参数
>>> print(1) 1 >>> print(1,2) 1 2 >>> print(1,2,3) 1 2 3
-
sep:多个数据之间的间隔默认是一个空格
' '
>>> print(1,2,3,sep = '!') 1!2!3
-
end:结尾默认
\n
>>> print(1,2,3,sep='#',end='哈哈') 1#2#3哈哈>>> print(1,2,3,sep='#',end='哈哈\n') 1#2#3哈哈 >>>
格式化输出
>>> name = "旺财"
>>> age = 18
>>> print(name,age)
旺财 18
>>> print("你叫旺财,你是18岁")
你叫旺财,你是18岁
>>> print("abc"+"ABC")
abcABC
>>> print("你叫"+name+",你是"+age+"岁")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> print("你叫%s,你是%d岁"%(name,age))
你叫旺财,你是18岁
- %s:表示字符串数据
- %d:表示整数数据
- %f:表示浮点型数据
input函数
获取用户的输入数据,输入的数据是一个字符串
>>> a = input("请输入你的年龄:")
请输入你的年龄:12
>>> a + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
如何获取多个数据的输入
>>> a,b,c = input("请输入三个数字:")
请输入三个数字:12,13,14
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)
>>> input("请输入三个数字:")
请输入三个数字:1,2,3
'1,2,3'
>>> a,b,c = eval(input("请输入三个数字:"))
请输入三个数字:1,2,3
>>> a+b+c
6
eval函数
解析字符串中的数字,整数,小数,其他进制的整数
>>> eval("3")
3
>>> eval("3.14")
3.14
>>> eval("WYZ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'WYZ' is not defined
>>> eval("0xABC")
2748
>>> eval("0x1001")
4097
>>> eval("0b1001")
9
int 函数
将整数字符串或浮点数转为整数
>>> int("123")
123
>>> int("3.14")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.14'
>>> int(3.14)
3
也可以去指定进制
>>> int("1001")
1001
>>> int("1001",2)
9
>>> int("1001",100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: int() base must be >= 2 and <= 36, or 0
>>> int("1001",3)
28
>>> int("1919",6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 6: '1919'
float 函数
将小数字符串或整数转换为浮点数
>>> float("3.14")
3.14
>>> float(3)
3.0
>>> float("3.1a4")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '3.1a4'
str函数
将对象转换成字符串类型
>>> a = 10
>>> str(a)
'10'
>>> name = "旺财"
>>> age = 10
>>> print(name+age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> print(name+str(age))
旺财10
abs函数
求绝对值
>>> abs(-10)
10
>>> abs(-10.2)
10.2
>>>
sum函数
求序列和
>>> sum([1,2,3])
6
>>> sum("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> sum(["abc","ABC","lala"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
1.3 运算符号
算数运算符
+
:加法;序列连接
>>> 1+2
3
>>> "abc"+"abc"
'abcabc'
>>> [1,2,3]+[1,2,3]
[1, 2, 3, 1, 2, 3]
-
:减法
>>> 3-2
1
>>> 3.14-2.89
0.25
*
:乘法;序列重复
>>> 2*3
6
>>> "abc"*3
'abcabcabc'
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
/
:除法,结果为小数
>>> 10/3
3.3333333333333335
>>> 9/2
4.5
//
:整除,如果存在小数,则结果为小数(整数+小数点)
>>> 10//3
3
>>> 9//2
4
>>> 10.0//3
3.0
>>> 9.0//2
4.0
**
:幂运算
>>> 2**4
16
>>> 81**0.5
9.0
%
:取余
>>> 10%3
1
>>> 10%-3
-2
>>> -10%3
2
>>> -10%-3
-1
>>> 7 % 4
3
>>> 7 % -4 # 3 -> 3 + -4 -> -1
-1
>>> -7 % 4 # 3 -> -3 + 4 -> 1
1
>>> -7 % -4
-3
赋值运算符
比较运算符
逻辑运算符
移位运算符