zoukankan      html  css  js  c++  java
  • python培训~函数

    2017年5月14日

    开始涉及函数

    练习题疑难解答:

     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 # 表格输出
     5 
     6 # prettytable
     7 
     8 # msg = "asdkfasfd\tasdfasdf\tasdfasdf\tasdfasdf\nasdkfasfd\tasdfasdf\tasdfasdf\tasdfasdf\n"
     9 # print(msg.expandtabs(20))
    10 
    11 # x y z
    12 # 5x + 3y + z/3 = 100  鸡的总价钱
    13 # x + y + z = 100  鸡的数量
    14 # x > 0; y > 0 z > 0
    15 
    16 # 0 < x < 20
    17 for x in range(1, 20):
    18     for y in range(1, 33):  # 严谨
    19         z = 100 - x - y  # 满足鸡的总数量
    20         # 判断满不满足条件
    21         # 鸡的价钱要对
    22         # z要是3的倍数
    23         if 5*x + 3*y + z/3 == 100 and z % 3 == 0:
    24             print("公鸡:{}只,母鸡:{}只,小鸡:{}只".format(x, y, z))

    第二次作业讲解

     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 # 个人账户文件:user|pwd|3|0
     5 # 商品文件
     6 # 查看商品分页展示
     7 # 购物历史模糊检索
     8 
     9 # users_list = []
    10 # f = open("users.txt", "r", encoding="utf-8")
    11 # # for line in f.readlines(): # 一下读到内存
    12 # for line in f: # 一下读到内存
    13 #     users_tmp = line.strip().split("|")  # 保存分割后的列表
    14 # f.close()
    15 #
    16 #
    17 #
    18 # while True:
    19 #     user_name = input("用户名:")
    20 #     pwd = input("密码:")
    21 #     pass
    22 
    23 # 商品列表
    24 # goods_list = []
    25 # with open("goods.txt", "r", encoding="UTF-8") as f:
    26 #     for line in f:
    27 #         goods_tmp = line.strip().split("|")
    28 #         goods_list.append(goods_tmp)
    29 # print(goods_list)
    30 #
    31 # for i in enumerate(goods_list, 1):
    32 #     print(i)
    33 #
    34 # # 分页
    35 # while True:
    36 #     shopping_cart = []
    37 #     page_num = input("请输入要浏览的页码数").strip()
    38 #     if page_num.isdigit():  # 判断输入的是不是数字
    39 #         page_num = int(page_num)  # 转成int类型
    40 #         # 判断是不是能被2整除
    41 #         # 能被2整除总页数就正好是 len(goods_list) / 2 页
    42 #         # 不能被2整除总页数就是(len(goods_list) / 2)+1页
    43 #         if page_num > 0 and len(goods_list) / 2 + 1:  # 输入的页码是有效的话
    44 #             start = (page_num -1) * 2
    45 #             end = page_num * 2
    46 #             for i in enumerate(goods_list[start:end], 1):
    47 #                 print(i)
    48 #             chosen = input("你要买啥:").strip()
    49 #             if chosen.isdigit():
    50 #                 chosen = int(chosen)
    51 #                 if 0< chosen <= len(goods_list[start:end]):
    52 #                     # 判断价格能不能购买
    53 #                     # 添加进购物车
    54 #                     shopping_cart.append(goods_list[start:end][chosen - 1])
    55 #                     print(goods_list[start:end][chosen - 1], "现已加入豪华午餐...")
    56 #                 else:
    57 #                     print("请从新输入...")
    58 #             # 输入Q退出
    59 #             elif chosen.upper() == "Q":
    60 #                 print("再见")
    61 #                 # 将购物历史写入文件
    62 #             else:
    63 #                 print("请重新输入...")
    64 
    65 
    66 # 购物历史的模糊检索
    67 # 字符串的in操作
    68 with open("history.txt", "r", encoding="UTF-8") as f:
    69 
    70     kw = input("请输入关键字:").strip()
    71     while True:
    72         for line in f:
    73             # 判断关键字是否在商品名上
    74             if kw in line.strip().split("|")[0]:
    75                 print(line)
    76         else:  # for 循环完整走完,没有break的时候走这个else
    77             print("没有找到相关记录...")
    78             break

    武sir第二次作业知识点讲解

     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 # 模糊匹配:
     5 
     6 # 1. 写入记录
     7 # f = open('log','a',encoding='utf-8')
     8 # f.write('\n百岁山|5.8|1')
     9 # f.close()
    10 
    11 # 2. 搜索
    12 # f = open('log','r',encoding='utf-8')
    13 # data = f.read()
    14 # f.close()
    15 # key = input('>>>请输入关键字:')
    16 # data_list = data.splitlines()
    17 # for item in data_list:
    18 #     if key in item:
    19 #         print(item)

    瞎驴老师对文件操作知识点的补充

     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 
     5 #意读r的方式打开文件
     6 # f=open('a.txt',encoding='utf-8',mode='r')
     7 # print(f)
     8 # data1=f.read()
     9 # print(data1)
    10 # print('=====================================')
    11 # data2=f.read()
    12 # print('data2====>',data2) #读不到内容
    13 # f.close()
    14 
    15 
    16 # f=open('a.txt',encoding='utf-8',mode='r')
    17 # f.read()
    18 #
    19 # print('=====================================')
    20 # f.seek(0)
    21 # data2=f.read()
    22 # print('data2====>',data2) #读不到内容
    23 # f.close()
    24 
    25 # f = open('a.txt', encoding='utf-8', mode='r')
    26 
    27 
    28 
    29 # f.close()
    30 # print(f.closed) #判断文件是否是关闭状态
    31 
    32 # print(f.encoding)
    33 # print(f.name)
    34 
    35 # print(f.readable()) #判断文件是否是r模式打开的
    36 
    37 # print(f.readline(),end='') #一次读一行
    38 # print(f.readline())
    39 # print(f.readline(),end='')
    40 
    41 
    42 # print(f.readlines()) #读取所有行的内容,存成列表的形式
    43 
    44 
    45 #以写w的方式打开文件:文件存在则清空,不存在则创建
    46 # f=open('a.txt','w',encoding='utf-8')
    47 # # f=open('b.txt','r',encoding='utf-8') #以读的方式打开文件,文件不存在则报错
    48 # f=open('b.txt','w',encoding='utf-8')
    49 # # print(f.writable())
    50 #
    51 # f.write('111111\n22222222')
    52 # f.seek(0)
    53 # f.write('\n333333\n444444')
    54 #
    55 # f.writelines(['\n55555\n','6666\n','77777\n'])
    56 # f.close()
    57 
    58 
    59 #文件的修改
    60 import os
    61 read_f=open('b.txt','r')
    62 write_f=open('.b.txt.swap','w')
    63 for line in read_f.readlines():
    64     if line.startswith('1111'):
    65         line='2222222222\n'
    66     write_f.write(line)
    67 read_f.close()
    68 write_f.close()
    69 os.remove('b.txt')
    70 os.rename('.b.txt.swap','b.txt')
     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 # s='林'
     5 # print repr(s)
     6 #
     7 # # s.encode('utf-8')
     8 # print s.decode('utf-8')
     9 #
    10 # print type(s)
    11 
    12 # s=u'林'
    13 #
    14 # # s.encode('utf-8')
    15 # # s.encode('gbk')
    16 #
    17 # # s.decode('utf-8')
    18 #
    19 # # print repr(s)
    20 # print s
    21 
    22 #uncide-----encode('utf-8')---->bytes
    23 #bytes-----encode('utf-8')---->uncide
    24 # s='林'
    25 # print s
    26 
    27 s=u''
    28 print s
     1 # -*- coding:gbk -*-
     2 #!/usr/bin/env python
     3 
     4 s=''
     5 #unicode(str)-----encode---->utf-8(bytes)
     6 #utf-8(bytes)-----decode---->unicode
     7 
     8 s2=s.encode('utf-8')
     9 # s.decode('utf-8') #报错
    10 # print(s)
    11 print(s2)
    12 
    13 # s2.encode('utf-8') #报错

    函数

      一、没有函数会出现哪些情况:

      * 无组织无结构,代码冗余
      * 可读性差
      * 无法统一管理且维护成本高

      二、函数分类

      * 内置函数

      * 自定义函数

     1 #内置函数
     2 # sum
     3 # max
     4 # min
     5 #
     6 # a=len('hello')
     7 # print(a)
     8 #
     9 # b=max([1,2,3])
    10 # print(b)
     1 #自定义函数
     2 
     3 # # ******
     4 # # ******
     5 # # ******
     6 # # hello world
     7 # # ******
     8 # # ******
     9 # # ******
    10 #
    11 def print_star():
    12     print('#'*6)
    13 
    14 def print_msg():
    15     print('hello world')
    16 
    17 print_star()
    18 print_star()
    19 print_star()
    20 print_msg()
    21 print_star()
    22 print_star()
    23 print_star()

      三、函数参数

      * 从大的角度去看,函数的参数分两种:形参(变量名),实参(值)

      

    1 #定义阶段
    2 # def foo(x,y): #x=1,y=2
    3 #     print(x)
    4 #     print(y)
    5 
    6 #调用阶段
    7 # foo(1,2)

      * 详细的区分函数的参数分为五种:

      位置参数,关键字参数,默认参数,可变长参数(*args,**kwargs),命名关键字参数

    1 #位置参数
    2 # def foo(x,y,z):#位置形参:必须被传值的参数
    3 #     print(x,y,z)
    4 #
    5 # # foo(1,2,3)
    6 # foo(1,2,3) #位置实参数:与形参一一对应
     1 #关键字参数:key=value
     2 
     3 def foo(x,y,z):
     4     print(x,y,z)
     5 
     6 # foo(z=3,x=1,y=2)
     7 
     8 #关键字参数需要注意的问题:
     9 # 1:关键字实参必须在位置实参后面
    10 # 2: 不能重复对一个形参数传值
    11 # foo(1,z=3,y=2) #正确
    12 # foo(x=1,2,z=3) #错误
    13 
    14 # foo(1,x=1,y=2,z=3)
     1 #默认参数
     2 
     3 # def register(name,age,sex='male'): #形参:默认参数
     4 #     print(name,age,sex)
     5 #
     6 # register('asb',age=40)
     7 # register('a1sb',39)
     8 # register('a2sb',30)
     9 # register('a3sb',29)
    10 #
    11 # register('钢蛋',20,'female')
    12 # register('钢蛋',sex='female',age=19)
    13 
    14 #默认参数需要注意的问题:
    15 #一:默认参数必须跟在非默认参数后
    16 # def register(sex='male',name,age): #在定义阶段就会报错
    17 #     print(name,age,sex)
    18 
    19 #(了解)二:默认参数在定义阶段就已经赋值了,而且只在定义阶段赋值一次
    20 # a=100000000
    21 # def foo(x,y=a):
    22 #     print(x,y)
    23 # a=0
    24 # foo(1)
    25 
    26 #三:默认参数的值通常定义成不可变类型
     1 #可变长参数
     2 def foo(x,y,*args): #*会把溢出的按位置定义的实参都接收,以元组的形式赋值给args
     3     print(x,y)
     4     print(args)
     5 #
     6 # foo(1,2,3,4,5)
     7 
     8 
     9 # def add(*args):
    10 #     res=0
    11 #     for i in args:
    12 #         res+=i
    13 #     return res
    14 # print(add(1,2,3,4))
    15 # print(add(1,2))
    16 
    17 
    18 
    19 # def foo(x, y, **kwargs):  # **会把溢出的按关键字定义的实参都接收,以字典的形式赋值给kwargs
    20 #     print(x, y)
    21 #     print(kwargs)
    22 # foo(1,2,a=1,name='egon',age=18)
    23 
    24 
    25 # def foo(name,age,**kwargs):
    26 #     print(name,age)
    27 #     if 'sex' in kwargs:
    28 #         print(kwargs['sex'])
    29 #     if 'height' in kwargs:
    30 #         print(kwargs['height'])
    31 #
    32 # foo('egon',18,sex='male',height='185')
    33 # foo('egon',18,sex='male')
     1 #命名关键字参数(了解)
     2 
     3 # def foo(name,age,*,sex='male',height):
     4 #     print(name,age)
     5 #     print(sex)
     6 #     print(height)
     7 # #*后定义的参数为命名关键字参数,这类参数,必须被传值,而且必须以关键字实参的形式去传值
     8 # foo('egon',17,height='185')
     9 
    10 
    11 
    12 # def foo(name,age=10,*args,sex='male',height,**kwargs):
    13 # def foo(name,age=10,*args,sex='male',height,**kwargs):
    14 #     print(name)
    15 #     print(age)
    16 #     print(args)
    17 #     print(sex)
    18 #     print(height)
    19 #     print(kwargs)
    20 #
    21 # foo('alex',1,2,3,4,5,sex='female',height='150',a=1,b=2,c=3)
    22 
    23 
    24 # def foo(*args):
    25 #     print(args)
    26 
    27 # foo(1,2,3,4) # 1,2,3,4 <=====>*(1,2,3,4)
    28 
    29 #*['A','B','C','D'],=====>'A','B','C','D'
    30 # foo(*['A','B','C','D']) #foo('A','B','C','D')
    31 # foo(['A','B','C','D']) #
    32 
    33 # def foo(x,y,z):
    34 #     print(x,y,z)
    35 #
    36 # # foo(*[1,2,3]) #foo(1,2,3)
    37 # foo(*[1,2]) #foo(1,2)
    38 
    39 
    40 # def foo(**kwargs):
    41 #     print(kwargs)
    42 #
    43 # #x=1,y=2  <====>**{'y': 2, 'x': 1}
    44 # # foo(x=1,y=2)
    45 #
    46 # foo(**{'y': 2, 'x': 1,'a':1}) #foo(a=1,y=2,x=1)
    47 
    48 # def foo(x,y,z):
    49 #     print(x,y,z)
    50 #
    51 # # foo(**{'z':3,'x':1,'y':2}) #foo(x=1,z=3,y=2)
    52 # foo(**{'z':3,'x':1}) #foo(x=1,z=3)
    53 
    54 
    55 # def foo(x,y,z):
    56 #     print('from foo',x,y,z)
    57 #
    58 # def wrapper(*args,**kwargs):
    59 #     print(args)
    60 #     print(kwargs)
    61 #
    62 #
    63 # wrapper(1,2,3,a=1,b=2)
    64 
    65 
    66 #
    67 # def foo(x,y,z):
    68 #     print('from foo',x,y,z)
    69 # def wrapper(*args,**kwargs):
    70 #     print(args) #args=(1,2,3)
    71 #     print(kwargs) #kwargs={'a':1,'b':2}
    72 #     foo(*args,**kwargs) #foo(*(1,2,3),**{'a':1,'b':2}) #foo(1,2,3,b=2,a=1)
    73 # # wrapper(1,2,3,a=1,b=2)
    74 # wrapper(1,z=2,y=3)
    75 
    76 
    77 
    78 # def foo(x,y,z):
    79 #     print('from foo',x,y,z)
    80 # def wrapper(*args,**kwargs):
    81 #     # print(args) #args=(1,)
    82 #     # print(kwargs) #kwargs={'y':3,'z':2}
    83 #     foo(*args,**kwargs) #foo(*(1,),**{'y':3,'z':2}) #foo(1,z=2,y=3)
    84 # # wrapper(1,2,3,a=1,b=2)
    85 # wrapper(1,z=2,y=3)
    86 #
    1 #补充:函数定义阶段到底干了什么事情:只检测函数体的语法,并不会执行
    2 # def bar():
    3 #     x
    4 #     if 1 >2:
    5 #           print('====>')
    6 #
    7 # bar()

      四、函数的返回值

     1 # def foo():
     2 #     print('from foo')
     3 #     return None
     4 # res=foo()
     5 # print(res)
     6 
     7 '''
     8 以三种情况返回值都为None:
     9 没有return
    10 return 什么都不写
    11 return None
    12 '''
     1 # def foo():
     2 #     print('from foo')
     3 #     x=1
     4 #     return x
     5 # res=foo()
     6 # print(res)
     7 
     8 #return 一个值  函数调用返回的结果就是这个值
     9 
    10 
    11 def foo():
    12     print('from foo')
    13     x=1
    14     return 1,[2,3],(4,5),{}
    15 # res=foo()
    16 # print(res) #打印结果:(1,[2,3],(4,5),{})
    17 # a,b,c,d=foo()
    18 # print(d)
    19 
    20 
    21 
    22 #return 值1,值2,值3,...   返回结果:(值1,值2,值3,...)
    23 
    24 # t=(1,2,3)
    25 # a,_,_=t
    26 # print(a)
    27 
    28 # t=(1,2,3,4,5,6,7,8,9)
    29 # a,*_,c=t
    30 # print(a)
    31 # print(c)

      五、调用函数

     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 def foo():
     5     print('from foo')
     6 
     7 def bar(name):
     8     print('bar===>',name)
     9 
    10 #按照有参和无参可以将函数调用分两种
    11 foo() #定义时无参,调用时也无需传入参数
    12 bar('egon') #定义时有参,调用时也必须有参数
    13 
    14 
    15 #按照函数的调用形式和出现的位置,分三种
    16 
    17 foo() #调用函数的语句形式
    18 
    19 def my_max(x,y):
    20     res=x if x >y else y
    21     return res
    22 
    23 # res=my_max(1,2)*10000000 #调用函数的表达式形式
    24 # print(res)
    25 
    26 
    27 res=my_max(my_max(10,20),30) #把函数调用当中另外一个函数的参数
    28 print(res)  

      六、自定义函数

     1 #!/usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 
     4 #为什么要定义函数?:先定义后使用,如果没有定义而直接使用,就相当于引用了一个不存在的变量名
     5 # foo()
     6 # def foo():
     7 #     print('from foo')
     8 # print(foo)
     9 
    10 #函数的使用包含两个阶段:定义阶段和使用阶段
    11 
    12 # 语法
    13 # def 函数名(参数1,参数2,...):
    14 #     """文档注释"""
    15 #     函数体
    16 #     return 值
    17 
    18 # x=len('hello')
    19 # print(x)
    20 
    21 
    22 #定义函数的三种形式
    23 #一:无参数函数:如果函数的功能仅仅只是执行一些操作而已,就定义成无参函数,无参函数通常都有返回值
    24 def print_star():
    25     print('#'*6)
    26 
    27 #二:定义有参函数:函数的功能的执行依赖于外部传入的参数,有参函数通常都有返回值
    28 # def my_max(x,y):
    29 #     res=x if x >y else y
    30 #     return res
    31 
    32 
    33 # 三元表达式
    34 x=10
    35 y=2
    36 # if x > y:
    37 #     print(x)
    38 # else:
    39 #     print(y)
    40 #
    41 # res=x if x > y else y
    42 # print(res)
    43 
    44 
    45 
    46 #三:空函数
    47 
    48 # def auth():
    49 #     """认证功能"""
    50 #     pass
    51 # auth()
    52 def insert():
    53     """插入功能"""
    54     pass
    55 def select():
    56     """查询功能"""
    57     pass
    58 def delete():
    59     """删除功能"""
    60     pass
    61 def update():
    62     """更新功能"""
    63     pass
  • 相关阅读:
    SQL反模式学习笔记16 使用随机数排序
    SQL反模式学习笔记21 SQL注入
    SQL反模式学习笔记22 伪键洁癖,整理数据
    SQL反模式学习笔记18 减少SQL查询数据,避免使用一条SQL语句解决复杂问题
    SQL反模式学习笔记19 使用*号,隐式的列
    SQL反模式学习笔记17 全文搜索
    SQL反模式学习笔记20 明文密码
    (可发送)亿级流量APP,是怎么做前端性能测试自动化的?
    测试窝 高薪测试必备技能和 20+ 项目实战精华,好书免费领(限前 1000 名)!
    同样是断言,为何 Hamcrest 如此优秀?测试灵魂三问,该如何回答?
  • 原文地址:https://www.cnblogs.com/jinxj/p/6866681.html
Copyright © 2011-2022 走看看