找回密码
 立即注册

推荐阅读

  • 便民服务
  • 关注我们
  • 社区新手
# 第 6讲 python 中的函数

# 1、什么时函数
# 1)函数:定义:函数是组织好的,可重复使用的,用来实现单一,或相关联功能 的代码段。
# 2)函数能提高应用的模块性,和代码的重复利用率。
# 3)python中提供了很多内建函数:print()
# 4)函数
# 内建函数:print()
# 自建函数:def 函数名()

# 2、自定义函数
# 可以使用def关键字来创建Python自定义函数,其基本语法结构如下:
# def 函数名(参数列表)
#     函数体
# 函数名()     #调用函数

# 例子1
# def test():
#     #这里是函数体 ,需要注意冒号,空一格tab键
#     print('duoceshi')

#第一种调用函数的方法
# test()    #调用函数,如果函数定义了,不调用不会输出结果,函数也可以在其他模块中调用

#第二种调用函数的方法
# __name__ 代表的时当前模块的名称(lesson6),__main__是被运行的模块名称,如果
# 两个相等就运行
# if __name__ == '__main__':     #这个是主函数,是函数的入口
#     test()                    #调用函数,main函数的代码是不会被其他模块导入

#第三种调用方法:在其他模块中调用函数
# 1)import dcs9.lesson6         #通过dcs9这个包名点模块名,进行调用
# 2)from dcs9 import lesson6    #通过包名导入模块名
# lesson6.test()               #通过模块名点函数名

# 3、函数中可带参数
# 1)单个参数
# def test(name):        #name 表示的是形式参数
#     '''
#     单个参数
#     :param name:
#     :return:
#     '''
#     print(name+'约会')
# test('孙悟空')      #孙悟空就是实际参数
# 注意:如果函数中带了参数,调用时如果没有参数会报错,多了也会报错

# 2)多个参数
# def test(name,where):     #传了两个形式参数
#     '''
#     多个参数
#     :param name:
#     :param where:
#     :return:
#     '''
#     print(name+'去'+where+'约会')
# test('孙悟空','花果山')           #调用函数时需要传两个实际参数

# 3)默认参数
# def test(name,where,action='约会'):     #当参数列表中出现形式参数和默认值参数,默认值参数只能放在后面
#     print(name+'去'+where+action)
#
# test('孙悟空','花果山')     #孙悟空去花果山约会   当不给默认值传参数,使用默认值
# test('孙悟空','花果山','吃桃')  #孙悟空去花果山吃桃  如果给了默认值新值就使用新值

# 4)可变长参数中的可变长元组 "*"表示的是可变长元组
# def test(*value):      #*号表示多个参数
#     print(value)
#     print(type(value))      #  <class 'tuple'>
#
# test('xiaoduan','xiaoming','xiaoliu')      #('xiaoduan', 'xiaoming', 'xiaoliu') 元组

# 5)可变长参数中的可变长字典 "**"表示的是可变长字典
# dict1 = {'name':'xiaoduan','age':18}
# dict2 = {'class':1833}
# def test(**value):
#     print(value)
# test(**dict1,**dict2)      #{'name': 'xiaoduan', 'age': 18, 'class': 1833}

# 6)可变长元组和可变长字典同时出现时,可变长字典需要放后面
# dict1 = {'name':'xiaoduan','age':18}
# def test(*value1,**value2):
#     print(value1)
#     print(value2)
# test('xiaoduan','xiaoming',**dict1)    #('xiaoduan', 'xiaoming')    {'name': 'xiaoduan', 'age': 18}



# 4、python 中函数变量和作用域
# 例子1:
# num = 100        #函数体外 是全局变量 局部变量 只在定义它的函数内部有效
# def test():
#     num = 200    #函数体内是局部变量
#     print(num)
# test()         #200
# print(num)     #100


# 例子2:
# num = 100
# def test():
#     num = 200     #如果函数体内部有定义变量就使用函数体内局部变量,如果没有使用全局变量
#     sum = num +100
#     print(sum)
#
# test()       #300
# print(num)   #100

# 例子3:
# num = 100
# def test():
#     global num      #把函数体内局部变量变为全局变量,原来的函数体外的全局变量失效了
#                      # global只能在函数体内使用
#     num = 200
#     sum = num +100
#     print(sum)
# test()            #300
# print(num)        #200


# 5、python 中的返回值return
'''
1、在程序开发中,有时候会希望一个函数执行程序结束后,告诉 调用者一个结果,以便调用者针对具体的结果做后续的处理。
2、返回值是函数完成工作后,最后给到调用者的一个结果。
3、在函数中使用return关键字可以返回结果。
4、调用函数的一方可以使用变量来接收函数的返回结果。
'''



# 例子1
# def test():
#     num = 600
#     score = num/6
#
# test()             #空
# print(test())     #None

# 例子2:
# def test():
#     num = 600
#     score = num/6
#     return score    #把score的结果给到函数调用处,谁拿到了这个函数谁就可以拿到这个score
#                     #return只是把结果返回回去,return后面的代码不会执行
# test()            #空
# print(test())     #100.0

# 例子3:
def test():
    num = 600
    score = num/6
    print(score)
    return score
test()           ##100.0
print(test())    #100.0



# 需求:编写一个求平均分的函数,然后根据平均分判断是否优秀学生
# def test():
#     num = 600
#     score = num/6
#     return score
#
# def goods_stu():
#     value = test()    #函数的传递
#     if value >90:
#         print('优秀学生')
#     else:
#         print('不是优秀学生')
#
# if __name__ == '__main__':
#     goods_stu()


# 需求:登录银行系统并显示余额,有两个功能第一个是登录,第二个是登录 后显示余额,
# 先登录然后根据登录是否成功然后是否显示余额。 分析思路:如果想查询到余额,前提必须登录,
# 所以现在我们用两个函数来 处理,第一个函数实现登录,第二个函数实现余额查询,
# 调用第一个函数得 到的结果给第二个函数,然后第二个函数根据结果进行代码处理。
# 登陆函数
# def login():
#     user = input('请输入您的用户名:')
#     if user=='admin':
#         pwd = input('请输入您的密码:')
#         if pwd =='123456':
#             return '登录成功'
#         else:
#             return '密码错误'
#     else:
#         return '用户名错误'
#
# # 查询余额
# def select_amount():
#     m = login()       #函数的传递
#     if m=='登录成功':
#         print('您的余额是$10000000')
#     else:
#         print('请重新登录')
# if __name__ == '__main__':
#     select_amount()

# 6、format()函数是一种格式化字符串的函数 ,该函数增强了字符串格式化的功能。
# 基本语法:是通过 {} 来代替以前的 %
# 1)按顺序进行格式化
# str1 = '{} {}'.format('hello','dcs',88)
# print(str1)         #hello dcs

# 2)通过索引进行格式化输出
# str1 = '{1} {0} {0}'.format('hello','dcs',88)    #大括号中的数字表示索引
# print(str1)          #dcs hello hello

# 3)通过参数名进行格式化输出
# str1 = '姓名:{name} 年龄:{age}'.format(name='xiaoduan',age='18')
# print(str1)          #姓名:xiaoduan 年龄:18

# 4)对列表进行格式化
# list1 = ['xiaoduan','18']
# str1 = '姓名:{0[0]} 年龄:{0[1]}'.format(list1)  #{0[0]}第一个0是取format中第一个值
# #第二个0是list1中的第一个值,
# print(str1)      #姓名:xiaoduan 年龄:18

# list1 = ['xiaoduan','18']
# list2=[16]
# str1 = '姓名:{0[0]} 年龄:{1[0]}'.format(list1,list2)
# #{1[0]} 这个1表示取list2,这个0是list2中第一个值
# print(str1)         #姓名:xiaoduan 年龄:16


# 5)对字典进行格式化
# dict1 = {'name':'xiaoduan','age':18}
# str1 = '姓名:{name} 年龄:{age}'.format(**dict1)    #zi'dian这里需要加*号
# print(str1)       #姓名:xiaoduan 年龄:18

# 7、zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成 一个个元组,
# 然后返回由这些元组组成的列表,如果各个迭代器的元素个 数不一致,
# 则返回列表长度与最短的对象相同。

# 例子1
# list1 = ['name','age','url']
# list2 = ['xiaoduan',18,'www.baidu.com']
# list3 = list(zip(list1,list2))
# print(list3)         #[('name', 'xiaoduan'), ('age', 18), ('url', 'www.baidu.com')]
# print(type(list3))   #<class 'list'>

# 例子2
# list1 = ['name','age','url']
# list2 = ['xiaoduan',18]
# list3 = list(zip(list1,list2))
# print(list3)           #[('name', 'xiaoduan'), ('age', 18)]   这里url不会打印出来,打印出与最短的list2相同

# 例子3
# list1          #{'name': 'xiaoduan', 'age': 18, 'url': 'www.baidu.com'}= ['name','age','url']
# # list2 = ['xiaoduan',18,'www.baidu.com']
# # list3 = dict(zip(list1,list2))
# # print(list3)

# 8、open() 函数用于打开一个文件,创建一个 file 对象 语法pen(file, mode),
# 模式有r(只读),w(写入覆盖),a(写入追加)

# 读 的模式  r
o = open(r'C:\my_project\dcs\dcs9\test','r')     #创建一个对象o
all= o.read()              #显示文件中所有的内容,数据类型是字符串
print(all)
print(type(all))            #<class 'str'>

all = o.readline()          #显示文件中第一行的内容  数据类型是字符串
print(all)                  #dcs

all = o.readlines()           #显示所有的内容,并且返回一个列表
print(all)                    #['dcs\n', 'china\n', '888\n', '666']
print(type(all))              #<class 'list'>


# 写的模式  w
o = open(r'C:\my_project\dcs\dcs9\test','w')
# o.write('duoceshi')        #write 对原文件的内容进行覆盖,不能写整型
o.writelines('123')         #对原文件的内容进行覆盖,不能写整型
o.close()                #关闭文件

# 追加模式 a
o = open(r'C:\my_project\dcs\dcs9\test','a')
# o.write('dcs')          #a模式对原文件进行追加,不会覆盖
o.writelines('hello\n')  #a模式对原文件进行追加,不会覆盖
o.close()

# 9、with open函数
with open(r'C:\my_project\dcs\dcs9\test','r') as f:     #读   f类似取个别名 即对象
    all = f.read()
    all1 = f.readline()
    all2 = f.readlines()

    print(all)
    print(all1)
    print(all2)         #['123dcshello\n', 'hello\n', '\n']


with open(r'C:\my_project\dcs\dcs9\test','w') as f:    #写
    # f.writelines('acb')
    f.write('efg')
    f.close()


with open(r'C:\my_project\dcs\dcs9\test','a') as f:    #追加
    f.writelines('acb')
    f.write('efg')
    f.close()



分享至 : QQ空间
收藏
您需要登录后才可以回帖 登录 | 立即注册