700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 学习笔记20:Python基础使用(参数 嵌套 列表 元组 字典 字符串等)

学习笔记20:Python基础使用(参数 嵌套 列表 元组 字典 字符串等)

时间:2021-11-10 22:34:27

相关推荐

学习笔记20:Python基础使用(参数 嵌套 列表 元组 字典 字符串等)

(1)函数的定义:可由字母,下划线和数字组成,但不能以数字开头,且不能与关键字相同

def 函数名(): 函数封装的代码

1

2

练习1:第一个函数

#注意定义函数之后只表示代码封装,需主动调用,函数定义必须写在调用之前 def say_hello(): """打招呼""" print("hello 1") print("hello 2")say_hello()

1

2

3

4

5

6

7

8

执行结果:C:\python\0\venv\Scripts\python.exe C:/python/0/first_函数.pyhello 1hello 2Process finished with exit code 0

1

2

3

4

5

6

注:函数定义上方与其他代码保留两个空行,且将函数说明用引号写在函数内部,在PyCharm中可用Ctrl+Q查看函数相关信息

(2)函数参数的使用:在函数名后面的括号内可填写参数,参数之间使用逗号进行分离;调用函数时按照参数定义(形参)顺序依次写入传递的参数值(实参)

函数的返回值:在函数中使用return关键字可返回函数值;当调用函数时可使用变量来接收函数的返回结果

练习2:两个数字的求和

def sum(number1,number2): """两个数字求和""" #调用函数,并使用result变量接收计算结果 result = number1 + number2 print("%d + %d = %d" %(number1,number2,result))sum(1,2)

1

2

3

4

5

6

执行结果:C:\python\0\venv\Scripts\python.exe C:/python/0/求和.py1 + 2 = 3Process finished with exit code 0

1

2

3

4

5

练习3:加入函数返回值

def sum(number1,number2): """两个数字求和""" result = number1 + number2 #可以使用返回值得出计算结果 return result#可以使用变量来接收函数执行的返回结果sum_result = sum(1,2)print("计算结果:%d" %sum_result)

1

2

3

4

5

6

7

8

执行结果:

C:\python\0\venv\Scripts\python.exe C:/python/0/求和.py计算结果:3Process finished with exit code 0

1

2

3

4

注意:return 表示返回,会返回到调用函数的位置,函数内return后续的代码不会被执行

(3)函数的嵌套

练习4:函数的嵌套

def test1(): print("*" * 50)def test2(): print("-" * 50) test1() print("+" * 50)test2()#打印任意字符任意次数的分隔线def print_line(char,times): print(char * times)print_line("&",40)def print_lines(char,times): """ 给函数添加文档注释:打印多条分割线 :param char:分隔线的字符 :param times:分隔线的次数 """ row = 1 while row < 3: print_line(char,times) row = row + 1print_lines("!",10)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

执行结果:C:\python\0\venv\Scripts\python.exe C:/python/0/函数嵌套.py--------------------------------------------------**************************************************++++++++++++++++++++++++++++++++++++++++++++++++++&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&!!!!!!!!!!!!!!!!!!!!Process finished with exit code 0

1

2

3

4

5

6

7

8

9

10

(4)模块中的函数:使用import导入模块;以py结尾的python源文件都是一个模块;在模块中的全局变量和函数都是模块可直接提供给外界的工具;模块名也是标识符不能以数字开头,不能与关键字重名,若模块名以数字开头则不能导入。

练习5:定义一个函数quadratic(a, b, c),求一元二次方程的方程解

import mathdef quadratic(a,b,c): if a == 0: return TypeError("a不能为0") if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)): return TypeError("Bad operand type") delta = math.pow(b,2) - 4*a*c if delta < 0: return "无实根" x1 = math.sqrt((delta)-b)/(2*a) x2 = -math.sqrt((delta)+b)/(2*a) return x1,x2a = int(input("请输入a:"))b = int(input("请输入b:"))c = int(input("请输入c:"))print(quadratic(a,b,c))

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

执行结果:D:\python\python程序\venv\Scripts\python.exe D:/python/python程序/方程解.py请输入a:2请输入b:8请输入c:4(1.224744871391589, -1.5811388300841898)Process finished with exit code 0

1

2

3

4

5

6

7

8

练习6:求n的阶乘

def fact(n): return fact_iter(n,1)def fact_iter(num,product): if num == 1: return product return fact_iter(num-1,num * product)print(fact(6))

1

2

3

4

5

6

7

执行结果:D:\python\python程序\venv\Scripts\python.exe D:/python/python程序/阶乘.py720Process finished with exit code 0

1

2

3

4

5

(5)pyc文件:使用解释器编译过的文件,即二进制文件(python解释器模块的源码转换为字节码,这样当用import导入时可优化执行速度。

(6)python中数据类型:数字型(整型,浮点型,布尔型,复数),非数字型(字符串,元组,列表,字典)

列表:多用在处理相同的数据类型,在其他语言中对应数组,用 [ ] 定义,数据之间用逗号隔开,列表的索引即位置标号从0开始,取值若超出索引范围则会index out of range出错。

练习7:列表基础使用

#按Ctrl+Q可以查看光标所在具体使用方法name_list= ["zhangshan","lisi","wangwu"]#1.取值和取索引print(name_list[2])print(name_list.index("wangwu"))#使用index方法时,取值必须存在#2.修改指定位置数据,列表指定索引不能超出范围name_list[1] = "李四"#3.向列表中增加数据name_list.append("三毛") #列表末尾追加数据name_list.insert(1,"喃喃")#在列表指定索引位置插入数据tmp_list = ["哪吒","熬丙","太乙真人"]name_list.extend(tmp_list)#将其他列表完整内容追加到当前列表print(name_list)#4.删除数据name_list.remove("wangwu")#可从列表中删除指定数据,若数据不只一个,则删除第一次出现的name_list.pop()#默认删除列表中最后一个元素name_list.pop(3)#可删除指定索引位置数据print(name_list)name_list.clear()#清空列表name_list1= ["zhangsan","lii","wang"]del name_list1[1]#del 关键字本质上是将一个变量从内存中删除,后续的代码则不能再使用这个变量,不建议使用print(name_list1)#统计name_list2 = ["zhangs","lii","wangs","uu","uu"]list_len = len(name_list2)print("列表中包含%d个元素" %list_len)print("uu出现了%d次"%name_list2.count("uu"))#排序name_list3 = ["bb","cc","tt","ff"]num1_list = [6,3,9,5,2]#升序#name_list3.sort()#num1_list.sort()#降序#name_list3.sort(reverse=True)#num1_list.sort(reverse=True)#逆序name_list3.reverse()num1_list.reverse()print(name_list3)print(num1_list)#打印python中的关键字,关键字后面不需要括号,如上面的delimport keywordprint(keyword.kwlist)#使用迭代(iteration)遍历列表,顺序从列表获取数据,每一次循环,数据会保存在name变量name_list4 = ["zhungs","lri","ue"]for name in name_list4: print("我的名字叫%s" %name)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

执行结果:C:\python\0\venv\Scripts\python.exe C:/python/0/列表.pywangwu2["zhangshan", "喃喃", "李四", "wangwu", "三毛", "哪吒", "熬丙", "太乙真人"]["zhangshan", "喃喃", "李四", "哪吒", "熬丙"]["zhangsan", "wang"]列表中包含5个元素uu出现了2次["ff", "tt", "cc", "bb"][2, 5, 9, 3, 6]["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"]我的名字叫zhungs我的名字叫lri我的名字叫ueProcess finished with exit code 0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

2.元组:与列表类似,但元组中的变量均不能修改;元组用定义,数据与数据之间用逗号隔开;元组的索引也从0开始;当元组中只有一个元素时,需要在元素后加入逗号

练习8:元组基础使用

info_tuple = ("魏无羡",26,1.8)#1.取值和取索引print(info_tuple[0])print(info_tuple.index(1.8))#2.统计计数print(info_tuple.count("魏无羡"))print(len(info_tuple))#3.使用迭代遍历元组for my_info in info_tuple: print(my_info)#使用格式字符串输出不方便,因为元组中保存的数据类型不同#4.使用格式化字符输出,格式化字符后面的‘’本身就是元组print("%s 年龄是 %d 身高是 %.2f" %("蓝忘机",20,1.8))info_tuple1 = ("蓝湛",20,1.8)print("%s 年龄是 %d 身高是 %.2f" %info_tuple1)info_str = "%s 年龄是 %d 身高是 %.2f" %info_tuple1 #使用元组可用来拼接新的字符串print(info_str)#元组和列表之间的转换info_tuple2 = ("魏婴",26,1.8)print(list(info_tuple2))

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

执行结果:C:\python\0\venv\Scripts\python.exe C:/python/0/元组.py魏无羡213魏无羡261.8蓝忘机 年龄是 20 身高是 1.80蓝湛 年龄是 20 身高是 1.80蓝湛 年龄是 20 身高是 1.80["魏婴", 26, 1.8]Process finished with exit code 0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

3.字典:存储多个数据,与列表有序的对象集合不同,字典是无序的;字典用{}定义;用键值对存储数据,键值对之间使用逗号分隔;键key是索引,值value是数据;键和值之间使用冒号分隔;键必须唯一;值可取任何数据类型,但键只能使用字符串,数字或元组

练习9:字典的基础使用

#字典是无序的数据集合,输出的顺序与定义的顺序无关lanzan = { "name":"蓝湛", "age": 20, "gender":True, "height":1.85 }print(lanzan)weiying_dict = {"name":"魏婴"}#1.取值print(weiying_dict["name"])#2.增加/修改weiying_dict["age"] = 27print(weiying_dict)weiying_dict["name"] = "魏无羡"print(weiying_dict)#3.删除weiying_dict.pop("name")print(weiying_dict)#4.统计键值个数print(len(lanzan))#5.合并字典tem_dict = {"weight":74.5, "age": 21}lanzan.update(tem_dict)print(lanzan)#6.清空字典lanzan.clear()print(lanzan)#7.循环遍历weiwuxian_dict = {"name":"魏无羡", "qq":"2423434", "phone":"3432545"}#k是每一次循环中获取到的键值对的keyfor k in weiwuxian_dict: print("%s - %s" %(k,weiwuxian_dict[k]))#字典和列表的联合使用:将多个字典放在一个列表中再进行遍历card_list = [ {"name":"魏无羡", "qq":"333333", "phone":"11111"}, {"name": "蓝忘机", "qq": "222222", "phone": "88888"},]for card_info in card_list: print(card_info)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

执行结果:C:\python\0\venv\Scripts\python.exe C:/python/0/字典.py{"name": "蓝湛", "age": 20, "gender": True, "height": 1.85}魏婴{"name": "魏婴", "age": 27}{"name": "魏无羡", "age": 27}{"age": 27}4{"name": "蓝湛", "age": 21, "gender": True, "height": 1.85, "weight": 74.5}{}name - 魏无羡qq - 2423434phone - 3432545{"name": "魏无羡", "qq": "333333", "phone": "11111"}{"name": "蓝忘机", "qq": "222222", "phone": "88888"}Process finished with exit code 0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

4.字符串:可用双引号或者单引号定义;len函数统计字符串长度;count统计子字符串在大字符串中出现的次数,若子字符串不存在则次数为0;index统计字符串在大字串中出现的位置,若子字符串不存在程序会报错。

练习10:字符串的基本使用

str1 = "hello python"str2 = "我爱看”陈情令""print(str2)print(str1[0])for char in str2: print(char)print(len(str1))print(str1.count("o"))print(str1.index("o"))space_str = " \t\n\r" #判断空白字符print(space_str.isspace())num_str = "\u00b2"#判断字符串是否只包含数字,下列三种均不能判断小数print(num_str)#平方print(num_str.isdecimal())#只能判断单纯的数字print(num_str.isdigit())#可判断单纯数字和unicode的数字print(num_str.isnumeric())#可判断单纯数字,中文数字和unicode的数字hell_str = "hello world"print(hell_str.startswith("Hello"))#判断是否以字符串开始print(hell_str.endswith("world"))#判断是否以字符串结束print(hell_str.find("o"))#判断子字符串在字符串中的位置,与index的区别在于当查找的字符不存在时不报错print(hell_str.replace("world","boji"))#替换字符串,会返回新字符串,但注意不会改变原有字符串print(hell_str)poem = ["\t\n白日依", "黄河", "入了海流\t\n"]for poem_str in poem: print("|%s|"% poem_str.strip().center(10,""))#strip去除空白字符,center中心对齐;ljust向左对齐;rjust向右对齐poem1 = "灯管\t 王之涣 \t白日依山尽 \t \n黄河"poem_list = poem1.split()#拆分字符串print(poem_list)result = " ".join(poem_list)print(result)#切片方法适用于字符串,列表,元组,可采用倒序顺序方法#字符串[开始索引:结束索引:步长]num_str = "01234567"print(num_str[2:6])print(num_str[2:])print(num_str[:6])print(num_str[-1:])print(num_str[:])print(num_str[::2])print(num_str[::-1])

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

C:\python\0\venv\Scripts\python.exe C:/python/0/字符串.py我爱看”陈情令"h我爱看”陈情令"1224True²FalseTrueTrueFalseTrue4hello bojihello world|白日依||黄河||入了海流|["灯管", "王之涣", "白日依山尽", "黄河"]灯管 王之涣 白日依山尽 黄河2345234567012345701234567024676543210Process finished with exit code 0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。