Python基本知识总结

基本语法

#号 注释一行
单引号,双引号 注释多行

 '''
多行注释
多行注释
 '''

 """
多行注释
多行注释
 """

Python通过缩进来控制语法的逻辑块判断,其他大部分语言用{} 来识别逻辑块代码,完成逻辑的判断。在Python中通过空格进行缩进,同一层次的逻辑块使用相同的缩进。
对于复合语句 在第一行结束后使用冒号(:)作为结尾,在冒号之后新起一行或多行默认归属于复合语句的下一个逻辑块代码,所以这个逻辑块代码缩进需要一致

for i in range(3):  # range([start,] stop,[step=1]) [] 为可选参数
	print(i)       #print 自动换行
	print("-"*10)  #打印10个 '-'
	
结果是:	
0
----------
1
----------
2
----------

\ 作为换行连接符(与C语言一样)

变量

变量声明中 无需声明变量类型 直接给变量赋值即可,赋值完成之后即可获得相应的变量属性

  int_num = 10
  float_num =10.00
  string = "hello world"
  print(int_num, float_num, string)
  
  结果:
  10 10.0 hello world

多点对多点的赋值操作

string1 = string2 = string3 = "hello world"
print(string1, string2, string3)

结果:
hello world hello world hello world

#赋值的位置需要一一对应
string1, string2, string3 = "hello", "world", "hello world"
print(string1, string2, string3)
结果:
hello world hello world

浮点数的操作

float_num =10.000			 
print(float_num)   	         #默认保留一位小数
print("%f" % float_num)  	 #保留小数点后6位,%简单理解为占位符,f为数据类型
print("%0.2f" % float_num)  #保留小数点后2位
print("%0.4f" % float_num)  #保留小数点后4位

结果
10.0
10.000000
10.00
10.0000

e记法(结果是一个浮点数)
如10进制的 15000 = 1.5e4 => 1.5乘以10的4次方,e代表10

print(1.5e4)
15000.0

字符串的操作

使用单引号或者双引号来标识赋值给变量的数据(单引号 和双引号在python中基本没有区别)

string1 = 'hello world'
string2 = "hello world"
print(string1,string2)

结果:
hello world hello world

可通过索引值对字符串变量进行操作,可随意提取变量中的字符,也可通过相应的操作生成新的字符串。

string = 'hello,world'
str1 = string[0]        #访问第0个元素
str2 = string[0:5]		#访问第0->4个元素 :可理解为一个箭头->
str3 = string[-1]		#访问最后一个元素
str4 = string[-5:]      #倒数第五个元素->最后一个元素
str5 = string[6:]		#第六个元素 -> 末尾
str6 = string[:5]		#第0个元素 ->第四个元素
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)

结果:
h
hello
d
world
world
hello

用内置的type()函数 可查明变量数据的类型

string ='sadasd'
print(type(string))
a = 10
print(type(a))
b = 10.0
print(type(b))
结果
<class 'str'>
<class 'int'>
<class 'float'>

isinstance() 用于判断类型是否与目标一致 返回值为布尔类型

print(isinstance(b,float))
结果
True

操作符

运算操作符

+ - * / %(取模) 求幂运算(**) 取整运算 //  (支持简化写法a+=b,a*=b...)
a = 5
b = 2
c = a + b   # 7
c = a - b	# 3
c = a / b	# 2.5  python3以后变成了真正的除法,结果为小数
c = a * b	# 10
c = a // b	# 2   相当于以前版本的除法
c = a ** b  # 25  5的二次方

比较操作符 返回值为布尔类型

== 判断两个值是否相等    相等返回True 反之 False
!= 判断两个值是否不相等  -----------------------
>  ---------------------------------------------
>= --------------------------------------------- 
<  ---------------------------------------------
<= ---------------------------------------------
多层比较的情况 
a == b == c  #a是否等于b且b是否等于c
a > b > c    #判断 a 是否大于b且b大于c

逻辑操作符

and    与运算    都为True 返回True 反之 False
or     或运算	 都为False 返回False 反之 True 
not    非运算     为True返回FalseFalse 返回True

优先级

上层的优先级比下层的高,同层之间左边的优先级比右边高,如比较运算符大于逻辑运算符,逻辑运算符中,not优先级大于and,and大于or
上层的优先级比下层的高,同层之间左边的优先级比右边高,如比较运算符大于逻辑运算符,逻辑运算符中,not优先级大于and,and大于or

条件判断语句

if 条件判断语句:
		代码块
	
if 条件判断语句:
		 代码块
else:
		 代码块
	 
if 条件判断语句:
	 	代码块
elif 条件判断语句:
	    代码块
else:
	 	代码块

循环

常用的 while for 循环语句
break 结束当次循环,并退出当前循环
continue 结束当次循环,直接开始当前循环的下次循环
pass 出现在循环控制语句中,不做任何操作,继续执行当次循环中的后续代码,该语句主要用于保存代码块的完整性
while 循环

num =0
while(num < 3):
  print("num is ", num)
  num +=1
结果:
num is  0
num is  1
num is  2

for 循环

num =10
for i in range(3):
	if i<num:
		print("i is ",i)
结果
i is  0
i is  1
i is  2

列表

列表是一种容器数据类型,容器数据类型的最大特点就是可以实现多种数据类型的嵌套,可将数字,字符串等类型数据嵌套到列表中,也能在列表中嵌套列表 列表用 [] 进行标识 列表的索引值规则和字符串一样。

list1 = [ "hello world", 100, 10.00 ]
list2 = [ "hello world", 100, 10.00, [1,2,3] ]
print(list1)	 # 输出整个list1
print(list1[0])	 # 输出列表的第一个元素
print(list1[1:]) # 输出从第二个索引开始至列表末尾的所有元素
print(list1[-1]) # 输出最后一个元素
print(list1 + list2)  #输出列表组合
结果
['hello world', 100, 10.0]
hello world
[100, 10.0]
10.0
['hello world', 100, 10.0, 'hello world', 100, 10.0, [1, 2, 3]]

列表成员的增加

list1 = [ "hello world", 100, 10.00 ]
print(list1)	 # 输出整个list1
list1.append('last')  #调用列表append方法追加成员,该方法只能追加一个成员
print(list1)     #输出追加后的List
list1.extend(['extend1','extend2'])  #调用extend方法追加多个成员(注意 该方法传递参数为一个列表)
print(list1)
list1.insert(1,'insert')#调用 insert方法,在指定位置插入成员
print(list1)
结果
['hello world', 100, 10.0]
['hello world', 100, 10.0, 'last']
['hello world', 100, 10.0, 'last', 'extend1', 'extend2']
['hello world', 'insert', 100, 10.0, 'last', 'extend1', 'extend2']

列表成员删除

list1 = [ "hello world", 100, 10.00 ,"pop_test"]
print(list1)	 # 输出整个list1
list1.remove('hello world') #remove()方法按照成员名删除
print(list1)     #输出追加后的List
# del 语句 
del list1[1]  #注 del 是语句 不是方法  del list1 (删除整个列表)
print(list1)
list1.pop() #pop方法 删除(弹出)最后一个成员(类比于c语言出栈),若传入参数可谓指定成员的索引值,删除指定成员 如 list1.pop(0) 删除第一个成员
print(list1)

结果
['hello world', 100, 10.0, 'pop_test']
[100, 10.0, 'pop_test']
[100, 'pop_test']
[100]

切片(分片)

list1 = [ "hello world", 100, 10.00 ,"pop_test"]
print(list1)	 # 输出整个list1
list2 = list1[0:2]  #用:进行切片 :可理解为 一个单项箭头 -> 取出 0->1 元素
print(list2)
list3 = list1[1:3] #取出第2->3元素
print(list3)
list4 = list1[:]  #取出全部的元素
print(list4)

结果
['hello world', 100, 10.0, 'pop_test']
['hello world', 100]
[100, 10.0]
['hello world', 100, 10.0, 'pop_test']

常用的操作符

list1 = [10]
list2 = [5]
print(list1 > list2) #比较运算符
print(list1 + list2) #拼接运算符
print(list1*3)       #乘法,重复操作符

list3 =[1,10,100]
print(1 in list3)     #成员运算符 判断是否为该列表成员
print(5 not in list3) ##成员运算符 判断是否不为该列表成员

list4 =[1,2,[3,4]]
print(list4[2][0])   #访问嵌套列表的成员(与C语言的二维数组类似)
结果
True
[10, 5]
[10, 10, 10]
True
True
3

元组

元组是另一种容器数据类型,用圆括号()进行标识,其基本性质,索引值和列表的是一样的,最大的区别是元组内的元素不能被重新赋值,元组也被称作只读列表。

函数

函数的定义

  1. 定义的开头使用 def 关键字 在关键字后面要紧跟函数名和括号()
    在括号内定义函数在被调用时需要传入的参数 括号以后以:结尾
  2. 在函数体内同一块逻辑代码使用相同的空格缩进。
  3. 在函数代码块的最后,可通过 return 关键字返回一个给该函数调用的方法,如果在return后没有接任何内容或者代码中没有return关键字,函数默认返回None给调用该函数的方法。
def function(str):  #定义
    print(str)
    return

function('hello') #调用

结果
hello 

参数

关键字参数,传入的参数与关键字匹配,与传入的顺序无关。

def function(str1,str2):  #定义两个参数
    print(str1 + str2)
    return
function('hello ',' world')  #正常调用

function('world ',' hello ')  

function(str2=' world',str1='hello ') #用关键字匹配
结果
hello  world
world  hello 
hello  world

可变参数(收集参数)

def function(*arg):      # 定义一个收集参数
    print("参数的个数是:", len(arg))
    print("第一个参数是:", arg[0])
    return
function('hello ',2,3,5)
结果
参数的个数是: 4
第一个参数是: hello 

lambda表达式

lambda 可省去函数的定义,直接定义运算表达式
定义 lambda [参数] : 参数的表达式

y = lambda x: x*2 +1  #单个参数
print(y(2))
y = lambda x ,z : x*z+5  #多参数
print(y(3,4))
5
17

字典

字典也是一种容器数据类型,但是较于列表和元组,操作更为复杂。其中一个区别就是列表和元组是有序的元素集合,字典却是无序的元素集合,为了达到对字典内的元素可控,在字典的每个元素都会加入相应的键值,对元素进行操作只能通过元素对应的键值来进行而不能使用在列表和元组中索引的方法。字典的标识符为大括号{} 。

dict = {}   #定义一个空的字典
dict["one"] = "This is one " 
dict[2] = "This is two "
dict_info = {"name": "Tang", "num":7272, "city": "GL"}

print(dict["one"])  			#输出键值为one的值
print(dict[2])					#输出键值为2的值
print(dict_info)				#输出整个dict_info 字典
print(dict_info.keys())			#输出 dict_info 的所有键值
print(dict_info.values())		#输出dict_info的所有值
This is one 
This is two 
{'name': 'Tang', 'num': 7272, 'city': 'GL'}
dict_keys(['name', 'num', 'city'])
dict_values(['Tang', 7272, 'GL'])

在Python中使用class关键词来创建一个类,在 class关键词之后紧接着的是类的名称,以冒号(:)结尾。在类的创建过程中需要注意的事项如下
(1)类变量:在创建的类中会定义一些变量,我们把这些变量叫
作类变量,类变量的值在这个类的所有实例之间是共享的,同时内部类或者外部类也能对这个变量的值进行访问。
(2)init():是类的初始化方法,我们在创建一个类的实例时
就会调用一次这个方法。
(3)self:代表类的实例(类比于C++的this指针),在定义类的方法时是必须要有的,但是在调用时不必传入参数。

class person():
    def __init__(self,x,y): #类的构造函数
        self.x=x
        self.y=y
    def fun(self):    #方法的定义
        print("person class is called")
        print(self.x,self.y)
        return

x = person(1,2)   #例化
x.fun()
person class is called
1 2

类的继承

class person(): #定义一个父类
    def __init__(self,x=1,y=2): #构造函数 x,y设为默认参数
        self.x=x
        self.y=y
        print("person class init")
    def fun(self):  #定义一个方法
        print("person class is called")
        print(self.x,self.y)
        return


class Bob(person):    #定义一个类 从person类继承
    def __init__(self):  #定义构造方法直接复制父类的构造函数
        super(Bob, self).__init__() #调用super方法复制父类的构造函数

    def fun1(self): #定义一个方法
        print("Bob class is called")

y = Bob() #例化一个Bob类
y.fun1()  #调用Bob 类方法
y.fun()   #调用父类方法
person class init
Bob class is called
person class is called
1 2

模块

模块即程序 以.py结尾的文件也是一个模块,一个 Python 源码文件除了可以被直接运行外,还可以作为模块(也就是库)被导入。
import 模块名
form 模块名 import 函数名
模块名可理解为一个命名空间,空间下封装了许多函数。

if name == ‘main

在脚本语言中没有C/C++那样 main 入口的概念,pyhon代码是逐行开始运行。在工程中我们会自己写一些模块,同时会导入一些其它模块。我们希望当前模块被直接运行,代码块就被运行。如果当前模块导入的其它模块中有代码块,我们希望被导入的模块的代码快不要被运行。就会用到上述关键字,其中 __name__是一个内置的变量。简而言之,该关键字相当于模拟了一个主函数的程序入口的功能,只会执行当前运行脚本的程序,其它被导入到当前脚本中的程序含有该关键字的程序不会被执行。
先建立一个 py_test.py 的文件(模块) 名 内容如下

str1 = "py_test_data"

def fun1():
    print("this is fun1 ")
    return
fun1()

该模块定义了一个字符串str1(为一个全局变量),一个函数 fun1(),并调用了该函数

this is fun1 

新建一个 py_.py的文件(模块) 内容如下

from py_test import  str1

def fun2(str1):
    print("this is fun2")
    print(str1)
fun2(str1)

该模块导入了 py_test.py 模块定义了一个fun2() 并调用了该函数, 打印第一个模块定义的str1字符串 ,运行py_.py模块,结果怕如下

this is fun1 
this is fun2
py_test_data

可以发现,在 py_test 模块的 fun1() 也被执行了,但是我们希望它不被执行,只是想打印str1字符串。将 py_test.py 修改如下

str1 = "py_test_data"

def fun1():
    print("this is fun1 ")
    return
if __name__ == "__main__":
    fun1()

if name == “main” 用以限制
重新运行 py_.py 模块

this is fun2
py_test_data

可以看到fun1()函数没有被调用, if name == “main” 类似于模拟了一个主函数入口的功能,执行的脚本不在py_test.py中(理解成不是主函数的入口),所以该关键字限制了函数的调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值