python语言学习|python学习001(语法基础篇)

## 前言:
### 1、运维/网络为什么要学习编程?
(1)运维/网络中所有已学的命令其实都是已经编制好的程序,创造命令就是编写程序;
(2)在云计算领域中,繁琐的命令配置已经不能满足日常需求,深入发展是需要贴近业务/研发的,因此就要能够创造命令/编写程序/开发;
(3)网络安全领域中,可以深入理解渗透、攻防等细节,Kali-Linux,SDN(命令对应网络)夯实技术;
(4)对于校招而言,大型互联网公司(一般指软件方面——阿里腾讯百度字节跳动)笔试题必考编程题{厂商提供设备服务(如深信服,华为,华3),奇安信做大数据的}。
### 2、为什么要选择学习python?
(1)Shell是Linux自带的编程语言,语法晦涩难懂,比C更难理解,额外扩展功能少(基于Linux运行),但效率比较高;
(2)C/C++/JAVA入门门槛比较高,属于纯开发语言,不太适合运维/网络需求(快速,简单,明了);
(3)Python属于解释型语言,俗称脚本,简单易学,功能强大,综合应用能力很强,开源+社区人员多(更新学习等资源广阔)。
### 3、python应用于:
客户端方向,后台(后端/服务端-处理客户端发来的请求)、爬虫、嵌入式开发、自动化运维、网络安全方向、人工智能(主算法)。
### 4、本次课程目标(用时7天)
(1)掌握常用知识
(2)做题不是目的,学编程代码是学会告诉计算机要干什么(怎么告诉,暗号是什么,逻辑语序问题)
(3)学习编程思维去解决一些实际的计算问题
(4)针对校招,LeetCode:https://leetcode-cn.com/+牛客网刷题练习
### 5、推荐书籍及使用建议:
(1)《python语言程序设计》——主要教材
(2)《python基础教程 第三版》字典
(3)《python学习手册 第四版》字典
### 6、Python学习环境搭建
Linux下Redhat/centOS自带python2.X,本次课程需要用python3.X,如果想在Linux下学习需要更新python的版本;Windows学习的话在官网下载安装python的包。
安装步骤(一般可以百度到)
### 7、python的两种运行方式:
(1)命令行运行方式——cmd命令框输入python然后输入命令:快速方便,不易保存;
(2)脚本文件运行方式——:容易保存代码,操作麻烦;
8、Python源代码文件编辑软件有:VIM\VSCode/PyCharm
笔记工具下载:MarkDownPad格式编辑软件,Tyora:https://www.typora.io/
### 9、学习建议
【python语言学习|python学习001(语法基础篇)】(1)Python概念不好理解,多看多想;
(2)多敲!多敲!多敲!量变产生质变!
# 一、语法基础
## 1、软件定义
是指一系列按照特定顺序组成的计算机数据与指令的集合。
(1)数据:计算机所能够识别的一些数据。硬盘(永久存储)中有:avi,doc,txt,py |内存中有:常量,变量,函数,对象,类;
(2)指令:操作这些数据进行相关计算的步骤。
(3)软件执行流程:准备数据(初始化、加载数据到内存)——对数据进行操作。
由python写出的代码叫源代码,源代码不能够直接被计算机识别,将源代码编译成计算机所能够识别的机器码,然后计算机执行机器码即可。
## 2、软件的两种操作方式:
(1)图形化界面操作方式——简单明了,方便操作。
(1)命令行操作方式——不易保存。
## 3、高级编程语言分为两类
(1)静态编译型语言:C\C++\Java
编译:必须将源代码完全编译成机器码文件,再去执行机器码文件,运行程序。
静态:变量必须明确数据类型的定义。
(2)动态解释型语言:Python\JavaScript\Mathlab\Ruby\Go\PHP
动态:变量没有明确的数据类型定义。
解释:没有必要将代码完全编译成机器码,读取一句源码编译一句,计算机运行一句指令。
## 1.1基本数据
### 1、整数int ——通常也被称为整型,是零、正数和负数,不带小数点。
(1)表示数字的时候,我们也可以使用二进制、八进制、十进制、十六进制,打印出来的都是十进制。

>>> print(0b1001)#二进制 9 >>> print(0o1234)#八进制 668 >>> print(0x9c1a)#十六进制 39962 #打印出来一律十进制 >>> print(0x9w2y) File "", line 1 print(0x9w2y) ^ SyntaxError: invalid syntax#语法错误,无效语法

(2)Python的整数长度为32位(4字节),并且通常是连续分配内存空间的。Python在初始化环境的时候就在内存中划分一块空间自动创建一个小整数对象池,专门用于整数对象的存储(当然这块空间不是无限大,能保存数据有限)——小整数对象池,为了方便调用,避免后期重复生成。
(3)小整数对象池只包含-5~256,这些数据最常用,预先被python加载进内存,不再这个范围内,一律重新创建。

#id()函数:查看内存地址的函数>>> id(0)140719390856832>>> id(1)140719390856864>>> id(251)140719390864864>>> id(260)2082203003792#地址不再连续

>>> id(300) 13647696 >>> id(300) 13647712 >>> id(300) 13647680

### 2、浮点型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

### 3、复数complex——由实部和虚部组成:a+bj=complex(a,b)
>>> print(1+2) 3 >>> print(1+2j) (1+2j) >>> (1+2j)*(1-2j) (5+0j) >>> complex(1,2)*complex(1,-2) (5+0j)

### 4、布尔型bool
对与错,0和1,正和反,都是传统意义上的布尔类型。在python里,布尔类型只有两个True,False;布尔类型只能进行逻辑运算和比较运算。
>>> True + False 1 >>> True - False 1 >>> 3 > 2 True >>> 2 < 1 False >>> 3 > 2 and 2 < 1 False

### 5、None空值NoneType
(1)不能理解为数字0,要理解为空集。
>>> None + 1 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' #类型错误 >>> [None] * 10# 创建一个长度为10的列表(序列) 没有数据 但有空间 [None, None, None, None, None, None, None, None, None, None]

(2)空值和整数不能加法乘法运算,因为空值代表的是序列,和整数不是一个类型的。
(3)空值主要用在创建序列(列表)和面向对象编程中使用.
### 6、字符串str
字符串有三种表示形式:双引号,单引号,三引号(一般用于注释)
>>> print("HelloWorld") HelloWorld >>> print('你好') 你好 >>> print(" '' ") '' >>> print(' "" ') "" >>> print(' ' ') File "", line 1 print(' ' ') ^ SyntaxError: EOL while scanning string literal >>> print(' \' ') '

### 7、转义符(常见):
(1)' \\ ':反斜杠
(2)\':单引号
(3)\'':双引号
(4)\n:换行
(5)\t:横向制表符
>>> print(' \' ') ' >>> print("\") File "", line 1 print("\") ^ SyntaxError: EOL while scanning string literal#逻辑错误 >>> print("\\") \

### 8、变量
(1)变量:在程序运行过程中,值会发生改变的量;
(2)常量:在程序运行过程中,值不会发生改变的量(字面量——直接在代码中出现的数据);
(3)无论是变量还是常量,在创建时都会在内存中开辟一个空间,用于保存它们的值;
(4)在python中,一律皆对象,全在变量外面存
# Java中基本数据类型变量a,b 和 引用数据类型变量c d e int a = 3; int b = 8; #a,b存储的是小整数对象池里3,8的地址 Object c = new Object(); Object d = new Object(); #c,d 存储的是新数据的存储位置的地址 Object e = c; #将c存储的地址交付给e,所以此时c,e存储的是同一个对象

>>> 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#300不在小整数对象池范围内,每一个分别存储一次,所以三个地址不同 >>> num1 == num2 True

注意:==运算时不能一味比地址,还要比两个对象的内容是否相等
(5)Python中变量本身是没有数据类型约束的,它只是一个对象的引用,存的是对象数据的内存地址,只有数据对象之间有数据类型的区分。
(6)变量必须在赋值后才能引用
>>> print(num4) Traceback (most recent call last): File "", line 1, in NameError: name 'num4' is not defined#变量只有赋值后才能被调用

(7)变量可以连续赋值
>>> 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#不同的存储位置的1000

标识符
(1)所谓的标识符就是我们对变量、常量、函数、类等起的名称
(2)规定:
  • 第一个字符必须是字母或者下划线_;
  • 虽然Python支持中文,我们也可以使用中文来命名,但是不推荐使用;
  • 以下划线开头的话,在面向对象编程当中,有特殊含义-(私有);
  • 标识符的其他的部分由字母、数字、下划线组成;
  • 标识符对字母大小写敏感(即区分大小写);
  • 变量名全部小写,常量名全部大写(Python当中不存在常量PI = 3.14,本质还是一个变量);
  • 函数名用小写加下划线方式,等同于变量名;
  • 类名用大驼峰式命名方法:如果名称由多个单词组成,则每个单词首字母大写。
注意:变量的命名不要使用关键字和内置函数的名称!
>>> True = 2 File "", line 1 SyntaxError: cannot assign to True#True是关键字 >>> if = 3 File "", line 1 if = 3 ^ SyntaxError: invalid syntax#if是内置函数


关键字
指的是已经被高级编程语言赋予特殊含义的单词
>>> 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 "", line 1, in TypeError: 'int' object is not callable

因为Python中,一切皆对象,函数本身也是对象!(解决:退出在进入就会恢复原来的样子)
>>> id(2) 2034812864 >>> id(id) 45545184#存储id()函数程序的地址 >>> abc = id >>> abc(1) 2034812848 >>> id(1) 2034812848#abc等同于id,调用的是同一个对象 >>> 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 内置函数
1、print函数
(1)输出函数,将内容格式化的显示在控制台窗口
(2)print函数原型:
print(self, *args ,sep=' ',end='\n',file=None)

>>> a=1 >>> b=2 >>> c=3 >>> print(abc) Traceback (most recent call last): File "", line 1, in NameError: name 'abc' is not defined >>> print(a,b,c) 1 2 3

参数解释:
  • 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 "", line 1, in TypeError: can only concatenate str (not "int") to str >>> print("你叫%s,你是%d岁"%(name,age)) 你叫旺财,你是18岁

  • %s:表示字符串数据
  • %d:表示整数数据
  • %f:表示浮点型数据
2、input函数
(1)获取用户的输入数据——输入的数据是一个字符串
>>> a = input("请输入你的年龄:") 请输入你的年龄:12 >>> a + 1 Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str

(2)多个数据的输入
>>> a,b,c = input("请输入三个数字:") 请输入三个数字:12,13,14 Traceback (most recent call last): File "", line 1, in #错误示例 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

3、eval函数
解析字符串中的数字,整数,小数,其他进制的整数
>>> eval("3") 3 >>> eval("3.14") 3.14 >>> eval("WYZ") Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'WYZ' is not defined >>> eval("0xABC") 2748 >>> eval("0x1001") 4097 >>> eval("0b1001") 9

4、int 函数
(1)将整数字符串或浮点数转为整数
>>> int("123") 123 >>> int("3.14") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '3.14' >>> int(3.14) 3

(2)也可以指定进制转换
>>> int("1001") 1001 >>> int("1001",2) 9 >>> int("1001",100) Traceback (most recent call last): File "", line 1, in ValueError: int() base must be >= 2 and <= 36, or 0#范围是二进制到三十六进制>>> int("1001",3) 28 >>> int("1919",6) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 6: '1919'#1919超出六进制的范围不能转换

5、float 函数
将小数字符串或整数转换为浮点数
>>> float("3.14") 3.14 >>> float(3) 3.0 >>> float("3.1a4") Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: '3.1a4'

6、str函数
将对象转换成字符串类型
>>> a = 10 >>> str(a) '10' >>> name = "旺财" >>> age= 10 >>> print(name+age) Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str >>> print(name+str(age)) 旺财10#字符串拼接

7、abs函数
求绝对值
>>> abs(-10) 10 >>> abs(-10.2) 10.2 >>>

8、sum函数
求序列和
>>> sum([1,2,3]) 6 >>> sum("abc") Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> sum(["abc","ABC","lala"]) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str'


## 1.3 运算符号
1、算数运算符
+:加法;序列连接
>>> 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]

  • /:除法,结果为小数
>>> 2*3 6 >>> "abc"*3 'abcabcabc' >>> [1,2,3]*3 [1, 2, 3, 1, 2, 3, 1, 2, 3]

  • //:整除,如果存在小数,则结果为小数(非准确小数,只是整数+小数点)
>>> 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


    推荐阅读