python 语法
1、字符串多输出
# 字符串使用乘号做运算,是将字符串多次输出,输出次数就是乘号后面的数字 ”hello world " * 100
2、变量定义
# 在使用解释器执行python时,不能使用变量名输出变量值,需要使用print()输出 strnum = "200" print(strnum)
3、注释
# 这是单行注释 ''' 这是多行注释,连续3个单引号 ''' """ 这是多行注释,连续3个双引号 """
4、幂
# 2的10次方 2 ** 10
5、布尔和数字计算
# python中布尔跟数字计算时,true为1,false为0跟数字一起参与运算 flag = true # flag =1 a = 0 b = flag + a # b = 1 print(b)
6、input函数
# 终端会提示输入密码,并且保存到passwd中,input获取的时字符串类型 password = input("请输入密码:") print(password)
7、类型转换函数
# 将字符串转换为整数和浮点数
8、格式化输出
# 05d表示5不到5位数时前面用0补位 num = 1 print("学号是%05d" % num) # .2f表示保留2为小数 price = 7.51234 print("价格是%.2f" % price) print("学号是%05d, 价格是%.2f" % (num, price ))
9、变量命名
# 1、变量都用瞎写字母 # 2、多个单词之间用下划线
10、if语句代码块
if (5>3): print("5>3 true") print("if下方缩进的代码还是if的代码") print("没有缩进就不是if逻辑的代码") if (2>3): print("false") print("if下方缩进的代码还是if的代码") print("没有缩进就不是if逻辑的代码2")

11、非
if not 5<3: print("not 是非运算符")
12、continue 使用要注意死循环
i = 0 while i< 10: if i % 2 == 0: # 使用continue时,前面必须给i加1否则会死循环 i += 1 continue print(i) i += 1
13、python中代码缩进非常重要,缩进代表代码块的范围
14、print 不换行
# print默认会自动换行,使用end=””就不会换行 print("*",end = "") print("*",end = "---") print("*")

15、print换行
# 输出换行 print("")
16、函数
def mul_table(): i = 1 while i <= 9: j = 1 while j <= i: # end 中加个\t制表符,保证垂直方向对其 print("%d * %d = %d" % (j,i,i*j),end ="\t") j += 1 print("") i += 1 # 函数调用 mul_table()
17、函数参数
18、模块:每一个以py结尾的python源代码都是一个模块,可以使用import导入
19、列表List(数组)
int_list = [5,20,10,30,2] int_list.sort() print(int_list) int_list.sort(reverse = True) print(int_list) int_list.reverse() print(int_list)

20、List 方法 extend 将另外一个list的元素加到当前list末尾
int_list = [5,20,10,30,2] str_list = ["zhhangsan","lisi","wangwu"] str_list.extend(int_list) print(str_list)

21、del关键字
# del关键字本质是从内存中删除变量 str_list = ["zhhangsan","lisi","wangwu"] del str_list[2] print(str_list)

22、count用法
str_list = ["zhangsan","lisi","wangwu","zhangsan"] print(str_list.count("zhangsan"))

23、迭代遍历for循环
str_list = ["zhangsan","lisi","wangwu","zhangsan"] for item in str_list: print(item)
24、元组Tuple,格式化字符串后面的()就是元组
# 元组定义并且添加数据后,无法添加、修改、删除数据 info_tuple = ("张三",18, 180,18899996666) print(info_tuple[0]) # 获取某个元素的下标 print(info_tuple.index("张三")) # 获取某个元素在元组中出现的次数 print(info_tuple.count("张三")) print(len(info_tuple)) # 元组只包含一个元素时,后面要加上逗号,否则single_tuple = (10) 定义的时一个int型变量
single_tuple = (10,)
25、元组使用场景
info_tuple = ("张三",18, 180,18899996666) print("姓名:%s 年龄:%d 身高:%d 电话:%d" % info_tuple) foramt_str = "姓名:%s 年龄:%d 身高:%d 电话:%d" % info_tuple print(foramt_str)
26、元组和列表相互转化
info_tuple = ("张三",18, 180,18899996666) info_list = list(info_tuple) print(type(info_list)) int_list = [3,1,2,9,7,5] int_tuple = tuple(int_list) print(type(int_tuple))
27、字典定义和增删改查
dic = {"name":"张三"}
# 如果key不存在就是新增,存在就是修改
dic["name"] = "法外狂徒张三"
# 如果key不存在就是新增,存在就是修改
dic["age"] = 18
dic["phone"] = 18866668888
print(dic)
print(dic["name"])
dic.pop("phone")
print(dic)
28、字典的其他操作
dic = {"name":"张三",
"age": 18,
"phone":10086
}
# 统计键值对数量
print(len(dic))
tempdic = {"friend":"李四",
"age":36
}
# 字典合并使用update,如果两个字典有相同key则会覆盖
dic.update(tempdic)
print(dic)
# 清空字典
dic.clear()
print(dic)

29、字典的遍历
# 字典的遍历 dic = {"name":"张三", "age": 18, "phone":10086 } for key in dic: print("%s : %s" % (key,dic[key])) # 字典和列表结合使用 list_dic = [ {"name":"张三", "age": 18, "phone":10086 }, {"name":"李四", "age": 28, "phone":10010 }, {"name":"王五", "age": 38, "phone":10020 } ] # 输出字典信息 for dic in list_dic: print(dic) # 数次字典key和value for dic in list_dic: for key in dic: print("%s : %s" % (key,dic[key]))


30、字符串
str_hello = "hello python welcome" # count统计字串出现的次数 print(str_hello.count("l")) # 找出l在字符串中第一次出现的位置 print(str_hello.index("l")) # 循环输出字符串的每一个字符 for c in str_hello: print(c)
31、字符串操作
str = "0123456789" # 从第一个字符开始截取到末尾,strat的索引可以省略,end索引没有表示截取到末尾 print(str[0:]) print(str[:]) # 每个一个字符截取,步长为2,输出02468 print(str[::2]) # 每个一个字符截取,步长为2,输出13579 print(str[1::2]) # 截取末尾两个字符 print(str[-2:]) # 字符串逆序 print(str[-1::-1]) # 省略start 索引 print(str[::-1])
32、内置函数
str_list = ["a","bc","e","f"] print(len(str_list)) print(max(str_list)) print(min(str_list)) del(str_list[1]) print(str_list) # max 和min比较的时key dic = {"name":"张三", "age": 18, "phone":10086 } print(max(dic))

33、列表和元组的切片
int_list = [3,1,5,2,8,6,9] print(int_list[1:3]) int_tuple = (1,2,3,4,5,6) print(int_tuple[0:4])
34、列表和元组使用操作符
# 列表和元组何以用* 字典不可以,因为key不可重复 int_list = [3,1,5,2,8,6,9] print(int_list * 3) int_tuple = (1,2,3,4,5,6) print(int_tuple * 3) # +会产生新的列表或者元组 int_list1 = [1,2,3] int_list2 = [4,5,6] int_list3 = int_list1 + int_list2 print(int_list1) print(int_list3) int_tuple1 = (1,2) int_tuple2 = (3,4) int_tuple3 = int_tuple1 + int_tuple2 print(int_tuple1) print(int_tuple3) # extend不会产生新的元组或者列表 int_list4 = [7,8,9] int_list5 = [10,11,12] int_list4.extend(int_list5) print(int_list4) # append 不会拆分列表中的元素 int_list6 = [13,14,15] int_list7 = [16,17,18] int_list6.append(int_list7) print(int_list6)

35、 in 和not in 可以作用于字典、列表、元组、字符串
int_list = [3,1,5,2,8,6,9] int_list2 = [[3,1],5,2,8,6,9] print(9 in int_list) print(10 in int_list) print(10 not in int_list) print ([3,1] in int_list) print ([3,1] in int_list2) dic = {"name":"张三", "age": 18, "phone":10086 } print("name" in dic)
36、完整的for循环
# 完整的for循环 value = 1 int_list = [3,1,5,2,0,8,6,9] for item in int_list: if(item == 0): print("元素为0,结果异常,循环结束") break value *= item else: print("%s元素的累积为:%d" % (int_list,value)) value2 = 1 int_list2 = [3,1,5,2,4,8,6,9] for item in int_list2: if(item == 0): print("元素为0,结果异常,循环结束") break value2 *= item else: print("%s元素的累积为:%d" % (int_list2,value2))

37、id()的函数
# 使用id()可以查看变量再内存中的地址 a = 1 print(id(a)) print(id(1)) b = a print(id(b)) a = 2 print(id(a)) print(id(b))
38、 函数实参传递的是实数的引用,而不是实参的拷贝
ef test(num): print("实参%d在内存中的地址为:%d" %(num, id(num))) a = 10 print("变量%d在内存中的地址为:%d" % (a, id(a))) test(a)

39、函数返回值传递的也是引用
def test(): str_return = "hello world" print("字符串%s在内存中的地址为:%d" % (str_return, id(str_return))) return str_return result = test() print("函数返回值在内存中的地址为:%d" % id(result))

40、全局变量定义要放到所有函数的上方
# 全局变量定义在函数前面还是后面都可以,但是必须在函数执行前定义,定义在函数执行代码后就报错 num1 = 200 def a_fun(): print(num1) print(num2) print(num3) num2 = 199 a_fun() num3 = "定义在函数执行代码后面出错了"

41、函数定义时,前面和后面都要空两行
print("函数开头要跟其他代码空两行============================") def func_blank(): print("函数定义前面和后面都要空两行") print("函数末尾要跟其他代码空两行=====================")
42、全局变量不能在函数内部修改
# python 不允许函数内部修改全局变量,如果强制修改,函数内部自动生成同名局部变量 num = 200 def a_fun(): num = 999 # 此处num变成局部变量 print(num) def b_fun(): print(num) a_fun() b_fun()
43、强制修改全局变量
# 强制修改全局变量,需要使用global关键字 num = 200 def a_fun(): global num num = 999 # 此处num变成局部变量 print(num) def b_fun(): print(num) a_fun() b_fun()
def return_two_result_fun(): weather = 30 wet = 60 return weather, wet result = return_two_result_fun() print(result)
45、接收元组返回值
def return_two_result_fun(): weather = 30 wet = 60 return weather, wet weather, wet = return_two_result_fun() print(weather) print(wet)
46、交换两个变量
# 交换两个变量的值 a = 6 b = 7 a = a + b b = a - b a = a - b # python独有,两个等价 b, a = (a, b) b, a = a, b
47、=+操作符对于不可变类型变量int 和可变类型变量list的区别
# Shadows built-in name 'list' 警告提示不要使用list这个系统使用的名字 def add_equal_func(num, _list, _list1): # 对于int型,num+= num 等价于 num = num + num num += num print("num += num 改变了变量的内存地址:%d" % num) # 对于list ,list+= list本质时执行list.extend所以不等于list= list +list _list += _list print("list += list 没有改变变量内存地址: %s" % _list) _list1 = _list1 + _list1 print("list1 = list1 + list1 重新给变量内存分配了地址:%s" % _list1) gl_num = 10 gl_list = [1, 2, 3, 4, 5] gl_list1 = [1, 2, 3, 4, 5] add_equal_func(gl_num, gl_list, gl_list1) print("gl_num = %d" % gl_num) print("gl_list = %s" % gl_list) print("gl_list1 = %s" % gl_list1)

48、函数默认参数,可以定义多个,但是必须放到参数末尾,多个默认参数传参需要写全名
def default_parameter_fun(_not_default,_num=1, flag=True):
if flag:
_num += 1
print("默认参数起作用")
else:
print("非默认参数起作用")
default_parameter_fun(1)
default_parameter_fun(2,flag=False)

49、多值参数字典和元组,元组建议使用*args ,字典建议使用**kwargs
# *num代表num是一个元组参数,**dic代表dic是一个字典参数,使用时去掉*或者** ,输入元组参数可以生路圆括号,输入字典参数使用=赋值 def multi_para_fun(_num, *num, **dic): print(_num) print(num) print(dic) multi_para_fun(9, 1, 2, 3, 4, 5, 6, 7, 8, name="张三", age=18)

50、字典和元组的拆包
def multi_para_fun(*args, **kwargs): print(args) print(kwargs) # multi_para_fun(9, 1, 2, 3, 4, 5, 6, 7, 8, name="张三", age=18) # 元组和字典不能直接给*args, **kwargs直接传参,必须拆包后才可以传参 gl_num = (1, 2, 3, 4, 5, 6, 7, 8, 9) gl_dic = {"name": "张三", "age": 18} multi_para_fun(*gl_num, **gl_dic)

51、递归
# 计算 1+2+3+4+5+6+.... +n # sum(n) = sum(n-1) + n def _sum_fun(_n): if _n == 1: return 1 elif _n > 1: return _sum_fun(_n - 1) + _n else: return 0 print(_sum_fun(100))
52、dir函数
# dir()查看对象自带的属性和方法,_下划线开头的方法都是python自带的 _dic = {"name":"zhangsan", "age": 18, } print(dir(_dic))

53、类class定义
class Dog: # init函数中定义类的属性,生成实力对象时自动调用init方法 def __init__(self, _name): self.name = _name print("Dog类实例化了一个对象,名字为: %s " % self.name) def __del__(self): print("Dog实例对象: %s 即将销毁" % self.name) def __str__(self): return "我是一只实例化的Dog,我的名字叫做: %s " % self.name # 自定义的方法必须有默认参数self def Run(self): print("%s 正在奔跑" % self.name) my_dog = Dog("旺财") print(my_dog) my_dog.Run()
54、身份运算符is一般用于判断None
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [1, 2, 3, 4, 5, 6, 7, 8, 9] if a == b: print("value equal") if id(a) == id(b): print("address not equal") # None一般使用is判断 c = None if c is None: print("equal")
55、私有属性和私有方法加上两个下划线__
class Person: def __init__(self, name): self.name = name self.__salary = 0 def Work(self): print("you have salary") self.__salary += 10000 def __checkSalary(self): if self.__salary == 0: print("%s you need to work" % self.name) else: print("%s you work hard ,you have %d salary" % (self.name, self.__salary)) def secret(self): self.__checkSalary() p = Person("John") p.Work() p.secret()
56、单继承在圆括号内写上继承的父类
class Person: # Method 'Walk' may be 'static' 将self删除,并且加上 @staticmethod @staticmethod def Walk(): print("work") class Student(Person): def __init__(self, para_name): self.name = para_name s1 = Student("小明") s1.Walk()
57、重写父类和调用父类方法
class Person: # Method 'Walk' may be 'static' 将self删除,并且加上 @staticmethod @staticmethod def Walk(): print("person is walking") class Student(Person): def __init__(self, para_name): self.name = para_name # 重写父类方法,先调用父类方法,再实现自己的方法 @staticmethod def Walk(): super(Student, Student).Walk() print("student is walking") s1 = Student("小明") s1.Walk()
58、类属性和类方法,类方法需要加@classmethod修饰,类方法的第一个参数是cls,作用类似于实例方法的self
class Person: count = 0 def __init__(self): Person.count += 1 @classmethod def showCount(cls): print("Person 类一共有%d个实例化对象" % cls.count) class Student(Person): def __init__(self, para_name): super().__init__() self.name = para_name s1 = Student("小明") s2 = Student("小王") s3 = Student("小张") print(Person.count)
59、静态方法,@staticmethod修饰,一般不需要访问类属性和实例属性就可以定义为静态方法
class Person: # Method 'Walk' may be 'static' 将self删除,并且加上 @staticmethod @staticmethod def Walk(): print("person is walking") Person.Walk()
60、重写new方法,需要返父对象的new方法super().__new__(cls)
class Person: def __init__(self): print("Person init execute!") # 重写new方法需要返父对象的new方法super().__new__(cls) def __new__(cls, *args, **kwargs): print("new函数第一步分配内存空间,第二步返回内存空间的引用地址") return super().__new__(cls) p = Person()
61、单例模式
class Factory: instance = None init_flag = False def __init__(self): if self.init_flag: return print("Factory init execute!") self.init_flag = True # 重写new方法需要返父对象的new方法super().__new__(cls) def __new__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__new__(cls) return cls.instance f1 = Factory() f2 = Factory() print(f1) print(f2)
62、异常处理
try: x = int(input("Enter a number: ")) print("x输入正确!") except ValueError: print("输入的数字不正确") except Exception as e: print("未知错误%s" % e) else: print("没有出现异常时执行的代码") finally: print("无论是否出现异常都会执行的代码") print("异常捕捉之后的代码")
63、主动抛出异常,使用raise
def password_input(): password = input("请输入密码,长度至少为8位!") if len(password) < 8: ex = Exception("密码长度不够8位,请重新输入密码!") raise ex else: return password try: password_input() except Exception as e: print(e)
64、导入模块
# 导入模块优先搜索当前项目目录,然后才是系统目录,所以当前项目的文件名不能跟系统文件名重名,否则会导致异常 可以使用print(模块.__file)查看导入文件的完整路径 import 模块1 as 别名 from 模块1 import (全局变量、类名、函数等) from 模块1 import (全局变量、类名、函数等) as 别名 # 不推荐,多个模块重名没有提示 from 模块1 import *
65、导入模块注意事项
# 1、导入模块中的所有没有缩进的代码都会自动执行一遍,所以模块中用来测试的代码也会执行一遍, # 2为了解决此问题,可以使用__name__,如果是在模块内部运行,__name__的值就是 __main__ # 如果是被其他文件导入的,此时__name__值就是模块的名称 def operation_fun(): print("这里是导入模块功能代码") # 下面的代码是模块内部测试代码,被导入到其他文件中时,不会执行 if __name__ == "__main__": operation_fun()
66、包
66、文件操作
# 在文件末尾追加内容 file = open("hello.txt", "a") file.write(" welcome to china") file.close() # 读取文件 file = open("hello.txt", "r") text = file.read() print(text) file.close() # 覆盖写文件 file = open("hello.txt", "w") file.write(" welcome to china") file.close()
67、读取一行文件内容
# readlind 循环读取文件 file = open("hello.txt", "r") while True: line = file.readline() if not line: break print(line) file.close()
68、python2处理中文
# *_* coding:utf8 *_* # python2中处理中文需要加上上面的注释 hello_str = "hello world,你好 世界" print(hello_str) # *_* coding:utf8 *_* # python2中处理中文需要加上上面的注释 # python2 处理中文字符串要在字符串前加上u hello_str = u"hello world,你好 世界" for char in hello_str: print(char)
69、eval函数
# eval()接受一个字符串,会把它当作表达式,求值,然后返回结果;类似于js的eval,很强大但是不安全 input_str = input("请输入一个算数表达式: ") print(eval(input_str))

70、安装pygame
# 打开终端输入下面命令 pip install pygame

验证是否安装成功:终端输入如下面的命令就会打开默认游戏
python -m pygame.examples.aliens


浙公网安备 33010602011771号