1、编程的集中主要方式:

  1.   面向过程 》类 》》关键字class
  2.  
  3.   面向函数》函数 》》 关键字def
  4.  
  5.    面向过程》 过程 》》 关键字def

2、python 函数是逻辑和结构化的集合。函数的定义和调用:

  1. # Author : xiajinqi
  2. # 函数
  3. def _print() :
  4. print("hello world")
  5. return 0
  6.  
  7. #函数调用
  8. x= _print()
  9. # 函数返回结果
  10. print(x)
  11.  
  12. def _print() :
  13. print("hello world1")
  14. return 0
  15.  
  16. #过程 本质就是没有返回结果的函数
  17. def _print() :
  18. print("hello world2")
  19.  
  20. #函数调用
  21. x= _print()
  22. # 函数返回结果
  23. print(x)
  24.  
  25. E:\Users\xiajinqi\PycharmProjects\twoday\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/twoday/function.py
  26. hello world
  27. 0
  28. hello world2
  29. None
  30.  
  31. Process finished with exit code 0

3、函数的相互调用,以及使用函数的有点,减少重复代码,扩展性强。是逻辑更加清晰合理。

  1. # Author : xiajinqi
  2. # 函数
  3. import sys,time
  4. def logger():
  5. time_format ='%Y-%m-%d'
  6. time_current = time.strftime(time_format)
  7. with open("test100.txt","a+",encoding="utf-8") as f :
  8. f.write("log end %s \n" %time_current)
  9. return 0
  10.  
  11. def test2() :
  12. logger()
  13. print("第一次写入")
  14. return 0
  15.  
  16. def test1() :
  17. logger()
  18. print("第二次写入")
  19. return 0
  20.  
  21. def test3() :
  22. logger()
  23. print("第三次写入")
  24. return 0
  25.  
  26. def test4() :
  27. logger()
  28. print("第四次写入")
  29. return 0
  30.  
  31. test1()
  32. test2()
  33. test3()
  34. test4()

4、函数的值传递 。返回值。return 后面的代码不执行。并且return可以返回任意值。元组,数组等任意多个值,返回多个值时候是一个元组

  1. # 函数值传递,简单传递
  2. def _print_name(x):
  3. print("你的名字是 %s" %x)
  4. return 0
  5.  
  6. _print_name("xiajinqi")
  7.  
  8. # Author : xiajinqi
  9. # 函数值传递,定义返回值
  10. def _print_name(x):
  11. print("你的名字是 %s" %x)
  12. return x,['test1','test2','text3'],'test'
  13. print("return 后面的语句不执行")
  14.  
  15. _print_name("xiajinqi")
  16.  
  17. print(_print_name('xiajinqi'))

E:\Users\xiajinqi\PycharmProjects\twoday\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/twoday/function.py 你的名字是 xiajinqi 你的名字是 xiajinqi ('xiajinqi', ['test1', 'test2', 'text3'], 'test')

  1.  

Process finished with exit code 0

  1.  

5.函数值传递的几种方式。值传递、

  1. # Author : xiajinqi
  2. # 函数值传递,定义返回值
  3. def _print_name(x,y):
  4. print(x,y)
  5.  
  6. def _print_name1(x,y,z):
  7. print(x,y,z)
  8.  
  9. x = 100
  10. y = 200
  11.  
  12. _print_name(100,y=300) # 位置参数和关键字参数
  13.  
  14. _print_name1(100,200,z=100) #
  15. _print_name1(100,z=100,200) #报错,关键字参数不能再位置参数前面

6、不定参数的使用

  1. # Author : xiajinqi
  2. # 函数值传递,定义返回值
  3. def _print_name(x,y):
  4. print(x,y)
  5.  
  6. def _print_name1(x,y,z):
  7. print(x,y,z)
  8.  
  9. #默认参数 _print_name2(x,y=11,z)报错,位置参数不能再形式参数前面
  10. def _print_name2(x,y=11,z=222):
  11. print(x,y,z)
  12.  
  13. # 不定参数
  14. def _print_name4(x,*args):
  15. print(x)
  16. print(args)
  17. print(args[1])
  18.  
  19. # 传一个字典,把关键字转化为字典
  20. def _print_name5(**kwargs):
  21. print(kwargs)
  22.  
  23. x = 100
  24. y = 200
  25. test= ['test1','test2','test3']
  26. test1 = {'name':'xiajinqi','age':''}
  27.  
  28. _print_name(100,y=300) # 位置参数和形式参数
  29.  
  30. _print_name1(100,200,z=100) #
  31. #_print_name1(100,z=100,200) #报错,位置参数不能在形式参数前面
  32. _print_name2(100,2222,1000)
  33. _print_name4(100,*["","",''])
  34. _print_name4(*test)
  35. _print_name5(**test1)
  36. _print_name5(**{'name':'xiajinqi'})

7、全局变量和局部变量:

  1. # 字符串,整形等不能在局部变量中修改,列表、字典等可以在局部变量可以直接修改,如果不想改变,可以设置为元组
  2. name = "xiajinqi"
  3. age =88 #全局变量
  4. name1 = ['test','xiajinqi','wangwu']
  5. def change_name():
  6. age =100 #作用范围为函数范围内,只改变对全局变量没有影响
  7. global name #申明为全局变量
  8. name = "test"
  9. return 0
  10.  
  11. def change_name2():
  12. name1[0] = 'test2'
  13. return 0
  14.  
  15. change_name()
  16. print(age)
  17. change_name2()
  18. print(name1)
  19.  
  20. E:\Users\xiajinqi\PycharmProjects\twoday\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/twoday/function.py
  21. 88
  22. ['test2', 'xiajinqi', 'wangwu']
  23.  
  24. Process finished with exit code 0

8、作业题目,实现对haproxy配置文件实现增删改查

  1. #!/usr/bin/python
  2. #实现对nginx 配置文件实现增删改查
  3. #1查询
  4. #2增加
  5. #3、删除
  6. import time
  7. import shutil,os
  8. file_name = "nginx.conf"
  9.  
  10. #查找
  11. def file_serach(domain_name):
  12. flag = "false"
  13. list_addr = []
  14. with open(file_name,"r",encoding="utf-8") as f :
  15. for line in f :
  16. if line.strip() == "backend %s" %(domain_name) :
  17. list_addr.append(line)
  18. flag = "true"
  19. continue
  20. if line.strip().startswith("backend") and flag == "true" :
  21. flag = "false"
  22. continue
  23. if flag == "true" :
  24. list_addr.append(line)
  25.  
  26. return list_addr
  27.  
  28. #增加
  29. def file_add(domain_name,list):
  30. flag = "false"
  31. result = ''
  32. with open(file_name, "a+", encoding="utf-8") as f:
  33. for line in f:
  34. if line.strip() == "backend %s" % (domain_name):
  35. result = "" #表示已经存在0
  36. break
  37. if result != '' :
  38. print("不存在添加")
  39. f.write("backend %s\n" %(domain_name))
  40. for ip in list['server'] :
  41. f.write("\t\t server %s weight %s maxconn %s\n" %(ip,list['ip_weight'],list['ip_maxconn']))
  42. result = ''
  43. return result
  44.  
  45. def file_change(domain_name,list):
  46. del_reustl = file_del(domain_name)
  47. if del_reustl == 0 :
  48. file_add(domain_name,list)
  49. print ("test")
  50. else :
  51. return 0
  52.  
  53. #删除
  54. def file_del(domain_name):
  55. flag = "false"
  56. tmp_file_name="nginx.conf.bak"
  57. with open(file_name, "r", encoding="utf-8") as f1,\
  58. open(tmp_file_name, "w", encoding="utf-8") as f2:
  59. for line in f1:
  60. if line.strip() == "backend %s" % (domain_name):
  61. flag = "true"
  62. continue
  63. if line.strip().startswith("backend") and flag == "true":
  64. flag = "false"
  65. f2.write(line)
  66. continue
  67. if flag == "false":
  68. f2.write(line)
  69. file_rename(file_name,tmp_file_name)
  70. return 0
  71.  
  72. def file_rename(old_name,new_name):
  73. date_format = "%Y%m%d"
  74. date_now = time.strftime(date_format)
  75. shutil.move(old_name,"nginx.conf.20180410.bak")
  76. shutil.move(new_name,old_name)
  77.  
  78. while 1 :
  79. user_choice = input('''
  80. 1、查询配置文件
  81. 2、增加配置文件内容
  82. 3、删除配置文件
  83. 4、修改配置文件
  84. 5、退出
  85. ''')
  86. if user_choice == '' :
  87. domain_name = input("请输入你要查询的域名:")
  88. serach_reustl = file_serach(domain_name)
  89. print("查询结果".center(50, '*'))
  90. if not serach_reustl :
  91. print("查询结果不存在,3s后返回首页面")
  92. time.sleep(3)
  93. continue
  94. for line in serach_reustl:
  95. print(line.strip())
  96. continue
  97.  
  98. elif user_choice == '' :
  99. print('''增加配置文件内容,
  100. 例子:{"backend":"ttt.oldboy.org","record":{"server":"100.1.7.9","weight":"20","maxconn":"3000"}}"''')
  101. #输入字符串 eval 转化为列表
  102. domain_tite =input("backend:")
  103. ip_list = input("请输入IP,以,为分隔符").split(',')
  104. ip_weight = input("weight:")
  105. ip_maxconn = input("maxconn:")
  106. user_input_list = {'server':ip_list,'ip_weight':ip_weight,'ip_maxconn':ip_maxconn}
  107. add_result = file_add(domain_tite,user_input_list)
  108. if add_result == '' :
  109. print("输入的域名已经存在,请重新输入")
  110. else :
  111. print("添加成功")
  112.  
  113. elif user_choice == '' :
  114. domain_name = input("请输入你要删除的域名:")
  115. del_result = file_del(domain_name)
  116. if del_result == 0 :
  117. print("删除成功",del_result)
  118. else :
  119. print("失败",del_result)
  120.  
  121. elif user_choice == '' :
  122. print('''修改配置文件内容,
  123. 例子:{"backend":"ttt.oldboy.org","record":{"server":"100.1.7.9","weight":"20","maxconn":"3000"}}"''')
  124. #
  125. domain_tite = input("backend:")
  126. ip_list = input("请输入修改后IP,以,为分隔符").split(',')
  127. ip_weight = input("weight:")
  128. ip_maxconn = input("maxconn:")
  129. user_input_list = {'server': ip_list, 'ip_weight': ip_weight, 'ip_maxconn': ip_maxconn}
  130. add_result = file_change(domain_tite, user_input_list)
  131. if add_result == '' :
  132. print("更新域名不存在")
  133. else:
  134. print("更新成功")
  135.  
  136. elif user_choice == '':
  137. print("退出登录")
  138. exit()
  139. else :
  140. print("输入错误")
  141. continue

python 新手函数基础(函数定义调用值传递等)的更多相关文章

  1. 速战速决 (3) - PHP: 函数基础, 函数参数, 函数返回值, 可变函数, 匿名函数, 闭包函数, 回调函数

    [源码下载] 速战速决 (3) - PHP: 函数基础, 函数参数, 函数返回值, 可变函数, 匿名函数, 闭包函数, 回调函数 作者:webabcd 介绍速战速决 之 PHP 函数基础 函数参数 函 ...

  2. Python新手学习基础之函数-概念与定义

    什么是函数? 函数是可以实现一些特定功能的方法或是程序,简单的理解下函数的概念,就是你编写了一些语句,为了方便使用,把这些语句组合在一起,给它起一个名字,即函数名.使用的时候只要调用这个名字,就可以实 ...

  3. 11、Python函数基础(定义函数、函数参数、匿名函数)

    函数先定义函数,后调用 一.定义函数: 1.简单的规则: 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 (). 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数. 函 ...

  4. Python新手学习基础之函数-lambda函数

    lambda函数 在Python里除了用def定义函数外,还有一种匿名函数,也就是标题所示的lambda函数,它是指一类无需定义标识符(函数名)的函数或子程序. lambda函数的使用语法如下: la ...

  5. Python 入门基础8 --函数基础1 定义、分类与嵌套使用

    目录 零.了解函数 一.函数的组成 二.函数的定义 三.函数的使用 四.函数的分类 五.函数的嵌套使用 零.了解函数 1.什么是函数 在程序中函数就是具备某一功能的工具 2.为何用函数 为了解决以下问 ...

  6. JS基础研语法---函数基础总结---定义、作用、参数、返回值、arguments伪数组、作用域、预解析

    函数: 把一些重复的代码封装在一个地方,在需要的时候直接调用这个地方的代码就可以了 函数作用: 代码重用 函数的参数: 形参:函数定义的时候,函数名字后面的小括号里的变量 实参:函数调用的时候,函数名 ...

  7. 致Python初学者,Python常用的基础函数你知道有哪些吗?

    Python基础函数: print()函数:打印字符串 raw_input()函数:从用户键盘捕获字符 len()函数:计算字符长度 format(12.3654,'6.2f'/'0.3%')函数:实 ...

  8. Python新手入门基础

    认识 Python 人生苦短,我用 Python -- Life is short, you need Python 目标 Python 的起源 为什么要用 Python? Python 的特点 Py ...

  9. 4、java变量、函数、基本类型的值传递、分支、循环、流程控制

    一.全局变量(global).局部变量(local).动态变量(dynamic).静态变量(static) 在类中的变量为全局变量,在方法函数中为局部变量,局部变量必须有人为赋的初值,全局变量的初值是 ...

随机推荐

  1. 【Leetcode】【Easy】Path Sum

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  2. [问题记录]libpomelo的安装

    1. 描述: 按照github上的操作完成 Windows in your libpomelo project root directory open git bash and type in mkd ...

  3. myeclipse 复制项目不包含svn或CVS目录

    目前只记录到2个方法:(SVN和CVS都适用) 方法一:导出法 1.右击需要cp的目录,点击export,General/File System 2.next 3.确认你选择的目录,并勾选:Creat ...

  4. IOS AFN (第三方请求)

    什么是AFN全称是AFNetworking,是对NSURLConnection.NSURLSession的一层封装虽然运行效率没有ASI高,但是使用比ASI简单在iOS开发中,使用比较广泛 AFN的g ...

  5. jmeter报告优化---展示详细信息

    参考文档:https://www.cnblogs.com/puresoul/p/5049433.html 楼上博主写的还是很详细,在报告优化这块,但是在操作中也走了一些弯路,我改动了两个点才成功,根据 ...

  6. bzoj2331 [SCOI2011]地板

    Description lxhgww的小名叫“小L”,这是因为他总是很喜欢L型的东西.小L家的客厅是一个的矩形,现在他想用L型的地板来铺满整个客厅,客厅里有些位置有柱子,不能铺地板.现在小L想知道,用 ...

  7. 两个List中的补集

    /** * 获取两个List的不同元素 * @param list1 * @param list2 * @return */ private static List getDiffrent(List ...

  8. select下拉框之默认选项清空

    最近和小伙伴发现,select默认选项一般是提示信息,怎么才能让当我们点击下拉框时,可选的选项中没有默认的提示信息呢? 思路: 1.当点击下拉框时,让默认提示信息,即下拉框第一个选项移除. 2.当没有 ...

  9. js 实现图片无限横向滚动效果

    门户网站好多都有产品无线滚动展现的效果: 测试demo1 -- 非无缝滚动(可以看出来从头开始的效果): css样式如下: .box{ width: 1000px; border: 1px solid ...

  10. 【luogu P1351 联合权值】 题解

    题目链接:https://www.luogu.org/problemnew/show/P1351 做了些提高组的题,不得不说虽然NOIP考察的知识点虽然基本上都学过,但是做起题来还是需要动脑子的. 题 ...