Python基础语法.ipynb
注:下载附件ipynb文件到之前创建的da_learn文件,并在da_learn运行jupyter-lab.exe,点击打开即可进行交互式学习和练习哦!
1. 注释
注释就是告诉计算机,这行文字只是普通说明文字,不用执行
# 开头的是单行注释"""多行字符串用三个引号包裹,也常被用来做多行注释"""pass # 这行是空语句,一般用来占用一行备用或啥也不是a = 1 # 变量定义并赋值name="QQ" # 变量定义并赋值print("hello world!") # 打印函数,用于将传入的参数打印出来,以便观察print("hello %s!" % name) # 打印函数的参数格式化,以便动态修改打印的文字
hello world!hello QQ!
2.基础数据类型和运算符
"""1. 数值运算:+ 加- 减* 乘/ 除// 取整除% 模运算** 乘方2. 逻辑运算and 与or 或not 非> 大于>= 大于或等于< 小于<= 小于或等于3. 字符串格式化+ 拼接[num] 索引% 格式化%s 字符串 (采用str()的显示)%r 字符串 (采用repr()的显示)%c 单个字符%b 二进制整数%d 十进制整数%i 十进制整数%o 八进制整数%x 十六进制整数%e 指数 (基底写为e)%E 指数 (基底写为E)%f 浮点数%F 浮点数,与上相同%g 指数(e)或浮点数 (根据显示长度)%G 指数(E)或浮点数 (根据显示长度)%% 字符"%"format格式化"{} is a {}!".format("God", "girl")"""pass
# 整数运算a = 5 + 3 # 加print("5 + 3 = %d" % a)b = 5 - 3 # 减print("5 - 3 = %d" % b)c = 5 * 3 # 乘print("5 * 3 = %d" % c)d = 5 / 3 # 除print("5 / 3 = %d" % d)e = 5 // 3 # 除print("5 // 3 = %d" % e)f = 5 % 3 # 模运算print("5 %% 3 = %d" % f)g = 5 ** 3 # 乘方运算print("5 %% 3 = %d" % g)h = 5 * (2 + 1) - 1 # 优先级运算print("5 * (2 + 1) - 1 = %d" % h)
5 + 3 = 85 - 3 = 25 * 3 = 155 / 3 = 15 // 3 = 15 % 3 = 25 % 3 = 1255 * (2 + 1) - 1 = 14
# 浮点运算a = 5.0 + 3 # 加print("5.0 + 3 = %.2f" % a)b = 5.0 - 3 # 减print("5.0 - 3 = %.2f" % b)c = 5.0 * 3 # 乘print("5.0 * 3 = %.2f" % c)d = 5.0 / 3 # 除print("5.0 / 3 = %.2f" % d)e = 5.0 // 3 # 除print("5.0 // 3 = %.2f" % e)f = 5.0 % 3 # 模运算print("5.0 %% 3 = %.2f" % f)g = 5.0 ** 3 # 乘方运算print("5.0 %% 3 = %.2f" % g)h = 5.0 * (2 + 1) - 1 # 优先级运算print("5.0 * (2 + 1) - 1 = %.2f" % h)
5.0 + 3 = 8.005.0 - 3 = 2.005.0 * 3 = 15.005.0 / 3 = 1.675.0 // 3 = 1.005.0 % 3 = 2.005.0 % 3 = 125.005.0 * (2 + 1) - 1 = 14.00
# 布尔值 与 逻辑运算# True Falseprint("True: %s" % True)print("False: %s" % False)a = True and Trueprint("True and True: %s" % a)b = True and Falseprint("True and False: %s" % b)c = False and Trueprint("False and True: %s" % c)d = False and Falseprint("False and False: %s" % d)not_true = not Trueprint("not True: %s" % not_true)not_false = not Falseprint("not False: %s" % not_false)e = 1 == 1print("1 == 1: %s" % e)f = 1 != 1print("1 != 1: %s" % f)g = 1 == Trueprint("1 == True: %s" % g)h = 1 != Trueprint("1 != True: %s" % h)i = 0 == Falseprint("0 == False: %s" % i)j = 0 != Falseprint("0 != False: %s" % j)k = 5 > 3print("5 > 3: %s" % k)l = 5 >= 3print("5 >= 3: %s" % l)m = 3 < 5print("3 < 5: %s" % m)n = 3 <= 5print("3 <= 5: %s" % n)
True: TrueFalse: FalseTrue and True: TrueTrue and False: FalseFalse and True: FalseFalse and False: Falsenot True: Falsenot False: True1 == 1: True1 != 1: False1 == True: True1 != True: False0 == False: True0 != False: False5 > 3: True5 >= 3: True3 < 5: True3 <= 5: True
# 字符串运算a = "hello"b = " "c = "world"d = "!"s1 = a + b + c + dprint("s1 = %s" % s1)e = s[0]f = s[4]g = s[-1]print("e = %s\nf = %s\ng = %s" % (e, f, g))s2 = "%s%s%s%s" % (a, b, c, d)print("s2 = %s" % s2)s3 = "{}{}{}{}".format(a, b, c, d)print("s3 = %s" % s3)s4 = "{0} {0}{1}{2}{3}".format(a, b, c, d)print("s4 = %s" % s4)
s1 = hello world!e = hf = og = !s2 = hello world!s3 = hello world!s4 = hello hello world!
3. 集合运算
# 列表 可改变的序列# 定义一个空列表ls = []print("空列表ls:", ls)# 定义一个非空列表ls = [1, 2, 3, 4, 5, 6, 7, 8, 9]print("非空列表ls:", ls)print("列表长度 ls:", len(ls))# 列表追加元素ls.append(10)print("列表追加元素后 ls:", ls)# 从列表末尾删除元素ls.pop()print("从列表末尾删除元素后 ls:", ls)# 按照索引获取列表元素print("ls 第1个元素:", ls[0])print("ls 第2个元素:", ls[1])print("ls 最后1个元素:", ls[-1])# 越界访问列表元素# ls[4]# 切片a = ls[0:5]print("ls 切片[0:5]:", a)b = ls[:5]print("ls 切片[:5]:", b)c = ls[5:9]print("ls 切片[5:9]:", c)c = ls[5:]print("ls 切片[5:]:", c)d = ls[5:-1]print("ls 切片[5:-1]:", d)e = ls[0:5:1]print("ls 切片[0:5:1]:", e)f = ls[0:5:2]print("ls 切片[0:5:2]:", f)del ls[5]print("ls 删除第6个元素:", ls)ls1 = [1, 2]ls2 = [3, 4]ls3 = ls1 + ls2print("列表拼接 ls3:", ls3)ls1.extend(ls2)print("列表扩展 ls1:", ls1)is_in_list = 4 in ls3print("判断元素是否在列表中 4 in ls3:", is_in_list)#
空列表ls: []非空列表ls: [1, 2, 3, 4, 5, 6, 7, 8, 9]列表长度 ls: 9列表追加元素后 ls: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]从列表末尾删除元素后 ls: [1, 2, 3, 4, 5, 6, 7, 8, 9]ls 第1个元素: 1ls 第2个元素: 2ls 最后1个元素: 9ls 切片[0:5]: [2, 3, 4, 5]ls 切片[:5]: [1, 2, 3, 4, 5]ls 切片[5:9]: [6, 7, 8, 9]ls 切片[5:]: [6, 7, 8, 9]ls 切片[5:-1]: [6, 7, 8]ls 切片[0:5:1]: [1, 2, 3, 4, 5]ls 切片[0:5:2]: [1, 3, 5]ls 删除第6个元素: [1, 2, 3, 4, 5, 7, 8, 9]列表拼接 ls3: [1, 2, 3, 4]列表扩展 ls1: [1, 2, 3, 4]判断元素是否在列表中 4 in ls3: True
# 元组 不可改变的序列tup = (1, 2, 3, 4, 5, 6, 7, 8, 9)# 元组一旦生成则内部元素不可改变# tup[0] = 0print("tup 长度:", len(tup))print("tup 第1个元素:", tup[0])print("tup 最后1个元素:", tup[-1])a = tup[0:5]print("tup 切片[0:5]:", a)tup1 = (1, 2)tup2 = (3, 4)tup3 = tup1 + tup2print("切片拼接 tup3:", tup3)is_in_tup = 4 in tup3print("判断元素是否在元组中 4 in tup3:", is_in_tup)a, b, c, d = tup3print("解构元素 a: %d, b: %d, c: %d, d:%d" % ( a, b, c, d))
tup 长度: 9tup 第1个元素: 1tup 最后1个元素: 9tup 切片[0:5]: (1, 2, 3, 4, 5)切片拼接 tup3: (1, 2, 3, 4)判断元素是否在元组中 4 in tup3: True解构元素 a: 1, b: 2, c: 3, d:4
# 字典 键值对数据结构empty_dict = {}print("空字典:", empty_dict)filled_dict = {"one": 1, "two": 2, "three": 3}print("非空字典:", filled_dict)a = filled_dict["one"]print('字典取值 filled_dict["one"]:', a)b = filled_dict.get("one")print('字典取值 filled_dict.get("one"):', b)# flled_dict["nine"] # 获取不存在的键值会报错c = filled_dict.get("nine")print('字典取值 filled_dict.get("nine"):', c)d = filled_dict.get("nine", 9)print('字典取值 filled_dict.get("nine", 9):', d)filled_dict["four"] = 4print('字典插入新的键值对 filled_dict["four"]:', filled_dict)filled_dict.setdefault("five", 5)print('字典插入新的键值对 filled_dict.setdefault("five", 5):', filled_dict)filled_dict.setdefault("five", 0)print('字典插入新的键值对 filled_dict.setdefault("five", 0):', filled_dict)del filled_dict["four"]del filled_dict["five"]print('字典删除键值对 filled_dict:', filled_dict)m = {"four": 4, "five": 5}filled_dict.update(m)print('字典更新 filled_dict:', filled_dict)is_in_dict = "nine" in filled_dictprint('判断是否在字典中:', is_in_dict)keys = filled_dict.keys()print('字典中的所有键(key):', keys)values = filled_dict.values()print('字典中的所有值(value):', values)
空字典: {}非空字典: {'one': 1, 'two': 2, 'three': 3}字典取值 filled_dict["one"]: 1字典取值 filled_dict.get("one"): 1字典取值 filled_dict.get("nine"): None字典取值 filled_dict.get("nine", 9): 9字典插入新的键值对 filled_dict["four"]: {'one': 1, 'two': 2, 'three': 3, 'four': 4}字典插入新的键值对 filled_dict.setdefault("five", 5): {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}字典插入新的键值对 filled_dict.setdefault("five", 0): {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}字典删除键值对 filled_dict: {'one': 1, 'two': 2, 'three': 3}字典更新 filled_dict: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}判断是否在字典中: False字典中的所有键(key): dict_keys(['one', 'two', 'three', 'four', 'five'])字典中的所有值(value): dict_values([1, 2, 3, 4, 5])
# 集合empty_set = set()print("空集合:", empty_set)filled_set = {1, 2, 3, 4, 5, 4, 3, 2, 1}print("非空集合:", filled_set)filled_set.add(6)print("集合添加元素:", filled_set)filled_set.remove(6)print("集合删除元素:", filled_set)other_set = {3, 4, 5, 6, 7}a = filled_set & other_setprint("集合 交集:", a)b = filled_set | other_setprint("集合 并集:", b)c = filled_set - other_setprint("集合 差集:", c)
空集合: set()非空集合: {1, 2, 3, 4, 5}集合添加元素: {1, 2, 3, 4, 5, 6}集合删除元素: {1, 2, 3, 4, 5}集合 交集: {3, 4, 5}集合 并集: {1, 2, 3, 4, 5, 6, 7}集合 差集: {1, 2}
4.流程控制
# 分支判断# 单分支判断name = "QQ"if name != "":print("hello %s!" % name)# 双分支判断is_true = Trueif is_true:print("good!")else:print("bad!")# 多分支判断score = 66if score >= 80:print("优秀")elif score >= 60:print("及格")else:print("不及格")
hello QQ!good!及格
# 循环# for循环sum = 0for i in range(1, 11):print("for count: %d" % i)sum += iprint("1-10的数字之和: %d" % sum)# while循环sum = 0i = 10while i > 0:sum += iprint("while count: %d" % i)i -= 1print("10-1的数字之和: %d" % sum)
for count: 1for count: 2for count: 3for count: 4for count: 5for count: 6for count: 7for count: 8for count: 9for count: 101-10的数字之和: 55while count: 10while count: 9while count: 8while count: 7while count: 6while count: 5while count: 4while count: 3while count: 2while count: 110-1的数字之和: 55
5. 函数
# 将常用的代码块整理为函数,可以让代码更加整洁,可重复利用# 加法函数def sum(a, b):return a + bsum_int = sum(1, 3)print("sum_int:", sum_int)sum_str = sum("hello ", "world!")print("sum_str:", sum_str)sum_list = sum([1,2], [3, 4])print("sum_list:", sum_list)# 任意连续整数之和def sum_start_to_end(start, end):if not isinstance(start, int) or not isinstance(end, int):print("错误的起止参数类型: start: %s, end: %s" % (type(start), type(end)))return Noneif start > end:print("错误的起止参数: start: %s, end: %s" % (start, end))return Nonesum = 0for i in range(start, end+1):sum += ireturn sumstart = 1end = 100c = sum_start_to_end(start, end)print("sum %d to %d sum: %d:" % (start, end, c))
sum_int: 4sum_str: hello world!sum_list: [1, 2, 3, 4]sum 1 to 100 sum: 5050:
6. 类
# 类是代码对现实世界的抽象和模拟,同时可以对代码进行封装和管理class Animal(object):name = Nonedef __init__(self, name):self.name = namedef breathe(self):print("%s breathe" % self.name)@staticmethoddef grunt():print("*grunt*")class Human(Animal):def __init__(self, name):super(Human, self).__init__(name)#self.name = namedef say(self, msg):print("{name} say: {message}".format(name=self.name, message=msg))a = Human("Jack")a.grunt()a.breathe()a.say("hello")
*grunt*Jack breatheJack say: hello
7.模块
# 模块是文件级别的代码组织和管理方式,可以把常用的代码封装成一个模块便于代码复用,通常一个模块可以包含很多函数或者类# 官方提供的数学计算模块import math # 直接引入模块使用a = 16b = math.sqrt(a)print("%s 的开方结果:%s" % (a, b))from math import ceil, floor # 引入模块中的部分函数使用c = 3.7d = ceil(c)e = floor(c)print("%s 向上取证的结果: %s" % (c, d))print("%s 向下取证的结果: %s" % (c, e))import math as m # 引入模块并重命名使用print("math 模块的常量圆周率: %s" % m.pi)# 自定义模块# 示例1 单文件模块"""#tree.├── main.py├── service.py# cat service.py#!/usr/bin/python# -*- coding: UTF-8 -*-def coffee_service():print("you call coffee service!")# cat main.py#!/usr/bin/python# -*- coding: UTF-8 -*-import serviceif __name__ == "__main__":service.coffee_service()"""pass# 多文件模块示例"""#tree.├── main.py└── robot├── __init__.py├── robot1.py└── robot2.py#cat robot/robot1.py#!/usr/bin/python# -*- coding: UTF-8 -*-def robot1_action():print("I'm in robot1!")#cat robot/robot2.py#!/usr/bin/python# -*- coding: UTF-8 -*-def robot2_action():print("I'm in robot2!")#cat robot/__init__.py#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':print '作为主程序运行'else:print 'robot模块初始化'#cat main.py#!/usr/bin/python# -*- coding: UTF-8 -*-# 导入robot包from robot.robot1 import robot1_actionfrom robot.robot2 import robot2_actionrobot1_action()robot2_action()"""pass
16 的开方结果:4.03.7 向上取证的结果: 43.7 向下取证的结果: 3math 模块的常量圆周率: 3.141592653589793
