python 新手函数基础(函数定义调用值传递等)
1、编程的集中主要方式:
- 面向过程 》类 》》关键字class
- 面向函数》函数 》》 关键字def
- 面向过程》 过程 》》 关键字def
2、python 函数是逻辑和结构化的集合。函数的定义和调用:
- # Author : xiajinqi
- # 函数
- def _print() :
- print("hello world")
- return 0
- #函数调用
- x= _print()
- # 函数返回结果
- print(x)
- def _print() :
- print("hello world1")
- return 0
- #过程 本质就是没有返回结果的函数
- def _print() :
- print("hello world2")
- #函数调用
- x= _print()
- # 函数返回结果
- print(x)
- E:\Users\xiajinqi\PycharmProjects\twoday\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/twoday/function.py
- hello world
- 0
- hello world2
- None
- Process finished with exit code 0
3、函数的相互调用,以及使用函数的有点,减少重复代码,扩展性强。是逻辑更加清晰合理。
- # Author : xiajinqi
- # 函数
- import sys,time
- def logger():
- time_format ='%Y-%m-%d'
- time_current = time.strftime(time_format)
- with open("test100.txt","a+",encoding="utf-8") as f :
- f.write("log end %s \n" %time_current)
- return 0
- def test2() :
- logger()
- print("第一次写入")
- return 0
- def test1() :
- logger()
- print("第二次写入")
- return 0
- def test3() :
- logger()
- print("第三次写入")
- return 0
- def test4() :
- logger()
- print("第四次写入")
- return 0
- test1()
- test2()
- test3()
- test4()
4、函数的值传递 。返回值。return 后面的代码不执行。并且return可以返回任意值。元组,数组等任意多个值,返回多个值时候是一个元组
- # 函数值传递,简单传递
- def _print_name(x):
- print("你的名字是 %s" %x)
- return 0
- _print_name("xiajinqi")
- # Author : xiajinqi
- # 函数值传递,定义返回值
- def _print_name(x):
- print("你的名字是 %s" %x)
- return x,['test1','test2','text3'],'test'
- print("return 后面的语句不执行")
- _print_name("xiajinqi")
- 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')
Process finished with exit code 0
5.函数值传递的几种方式。值传递、
- # Author : xiajinqi
- # 函数值传递,定义返回值
- def _print_name(x,y):
- print(x,y)
- def _print_name1(x,y,z):
- print(x,y,z)
- x = 100
- y = 200
- _print_name(100,y=300) # 位置参数和关键字参数
- _print_name1(100,200,z=100) #
- _print_name1(100,z=100,200) #报错,关键字参数不能再位置参数前面
6、不定参数的使用
- # Author : xiajinqi
- # 函数值传递,定义返回值
- def _print_name(x,y):
- print(x,y)
- def _print_name1(x,y,z):
- print(x,y,z)
- #默认参数 _print_name2(x,y=11,z)报错,位置参数不能再形式参数前面
- def _print_name2(x,y=11,z=222):
- print(x,y,z)
- # 不定参数
- def _print_name4(x,*args):
- print(x)
- print(args)
- print(args[1])
- # 传一个字典,把关键字转化为字典
- def _print_name5(**kwargs):
- print(kwargs)
- x = 100
- y = 200
- test= ['test1','test2','test3']
- test1 = {'name':'xiajinqi','age':''}
- _print_name(100,y=300) # 位置参数和形式参数
- _print_name1(100,200,z=100) #
- #_print_name1(100,z=100,200) #报错,位置参数不能在形式参数前面
- _print_name2(100,2222,1000)
- _print_name4(100,*["","",''])
- _print_name4(*test)
- _print_name5(**test1)
- _print_name5(**{'name':'xiajinqi'})
7、全局变量和局部变量:
- # 字符串,整形等不能在局部变量中修改,列表、字典等可以在局部变量可以直接修改,如果不想改变,可以设置为元组
- name = "xiajinqi"
- age =88 #全局变量
- name1 = ['test','xiajinqi','wangwu']
- def change_name():
- age =100 #作用范围为函数范围内,只改变对全局变量没有影响
- global name #申明为全局变量
- name = "test"
- return 0
- def change_name2():
- name1[0] = 'test2'
- return 0
- change_name()
- print(age)
- change_name2()
- print(name1)
- E:\Users\xiajinqi\PycharmProjects\twoday\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/twoday/function.py
- 88
- ['test2', 'xiajinqi', 'wangwu']
- Process finished with exit code 0
8、作业题目,实现对haproxy配置文件实现增删改查
- #!/usr/bin/python
- #实现对nginx 配置文件实现增删改查
- #1查询
- #2增加
- #3、删除
- import time
- import shutil,os
- file_name = "nginx.conf"
- #查找
- def file_serach(domain_name):
- flag = "false"
- list_addr = []
- with open(file_name,"r",encoding="utf-8") as f :
- for line in f :
- if line.strip() == "backend %s" %(domain_name) :
- list_addr.append(line)
- flag = "true"
- continue
- if line.strip().startswith("backend") and flag == "true" :
- flag = "false"
- continue
- if flag == "true" :
- list_addr.append(line)
- return list_addr
- #增加
- def file_add(domain_name,list):
- flag = "false"
- result = ''
- with open(file_name, "a+", encoding="utf-8") as f:
- for line in f:
- if line.strip() == "backend %s" % (domain_name):
- result = "" #表示已经存在0
- break
- if result != '' :
- print("不存在添加")
- f.write("backend %s\n" %(domain_name))
- for ip in list['server'] :
- f.write("\t\t server %s weight %s maxconn %s\n" %(ip,list['ip_weight'],list['ip_maxconn']))
- result = ''
- return result
- def file_change(domain_name,list):
- del_reustl = file_del(domain_name)
- if del_reustl == 0 :
- file_add(domain_name,list)
- print ("test")
- else :
- return 0
- #删除
- def file_del(domain_name):
- flag = "false"
- tmp_file_name="nginx.conf.bak"
- with open(file_name, "r", encoding="utf-8") as f1,\
- open(tmp_file_name, "w", encoding="utf-8") as f2:
- for line in f1:
- if line.strip() == "backend %s" % (domain_name):
- flag = "true"
- continue
- if line.strip().startswith("backend") and flag == "true":
- flag = "false"
- f2.write(line)
- continue
- if flag == "false":
- f2.write(line)
- file_rename(file_name,tmp_file_name)
- return 0
- def file_rename(old_name,new_name):
- date_format = "%Y%m%d"
- date_now = time.strftime(date_format)
- shutil.move(old_name,"nginx.conf.20180410.bak")
- shutil.move(new_name,old_name)
- while 1 :
- user_choice = input('''
- 1、查询配置文件
- 2、增加配置文件内容
- 3、删除配置文件
- 4、修改配置文件
- 5、退出
- ''')
- if user_choice == '' :
- domain_name = input("请输入你要查询的域名:")
- serach_reustl = file_serach(domain_name)
- print("查询结果".center(50, '*'))
- if not serach_reustl :
- print("查询结果不存在,3s后返回首页面")
- time.sleep(3)
- continue
- for line in serach_reustl:
- print(line.strip())
- continue
- elif user_choice == '' :
- print('''增加配置文件内容,
- 例子:{"backend":"ttt.oldboy.org","record":{"server":"100.1.7.9","weight":"20","maxconn":"3000"}}"''')
- #输入字符串 eval 转化为列表
- domain_tite =input("backend:")
- ip_list = input("请输入IP,以,为分隔符").split(',')
- ip_weight = input("weight:")
- ip_maxconn = input("maxconn:")
- user_input_list = {'server':ip_list,'ip_weight':ip_weight,'ip_maxconn':ip_maxconn}
- add_result = file_add(domain_tite,user_input_list)
- if add_result == '' :
- print("输入的域名已经存在,请重新输入")
- else :
- print("添加成功")
- elif user_choice == '' :
- domain_name = input("请输入你要删除的域名:")
- del_result = file_del(domain_name)
- if del_result == 0 :
- print("删除成功",del_result)
- else :
- print("失败",del_result)
- elif user_choice == '' :
- print('''修改配置文件内容,
- 例子:{"backend":"ttt.oldboy.org","record":{"server":"100.1.7.9","weight":"20","maxconn":"3000"}}"''')
- #
- domain_tite = input("backend:")
- ip_list = input("请输入修改后IP,以,为分隔符").split(',')
- ip_weight = input("weight:")
- ip_maxconn = input("maxconn:")
- user_input_list = {'server': ip_list, 'ip_weight': ip_weight, 'ip_maxconn': ip_maxconn}
- add_result = file_change(domain_tite, user_input_list)
- if add_result == '' :
- print("更新域名不存在")
- else:
- print("更新成功")
- elif user_choice == '':
- print("退出登录")
- exit()
- else :
- print("输入错误")
- continue
python 新手函数基础(函数定义调用值传递等)的更多相关文章
- 速战速决 (3) - PHP: 函数基础, 函数参数, 函数返回值, 可变函数, 匿名函数, 闭包函数, 回调函数
[源码下载] 速战速决 (3) - PHP: 函数基础, 函数参数, 函数返回值, 可变函数, 匿名函数, 闭包函数, 回调函数 作者:webabcd 介绍速战速决 之 PHP 函数基础 函数参数 函 ...
- Python新手学习基础之函数-概念与定义
什么是函数? 函数是可以实现一些特定功能的方法或是程序,简单的理解下函数的概念,就是你编写了一些语句,为了方便使用,把这些语句组合在一起,给它起一个名字,即函数名.使用的时候只要调用这个名字,就可以实 ...
- 11、Python函数基础(定义函数、函数参数、匿名函数)
函数先定义函数,后调用 一.定义函数: 1.简单的规则: 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 (). 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数. 函 ...
- Python新手学习基础之函数-lambda函数
lambda函数 在Python里除了用def定义函数外,还有一种匿名函数,也就是标题所示的lambda函数,它是指一类无需定义标识符(函数名)的函数或子程序. lambda函数的使用语法如下: la ...
- Python 入门基础8 --函数基础1 定义、分类与嵌套使用
目录 零.了解函数 一.函数的组成 二.函数的定义 三.函数的使用 四.函数的分类 五.函数的嵌套使用 零.了解函数 1.什么是函数 在程序中函数就是具备某一功能的工具 2.为何用函数 为了解决以下问 ...
- JS基础研语法---函数基础总结---定义、作用、参数、返回值、arguments伪数组、作用域、预解析
函数: 把一些重复的代码封装在一个地方,在需要的时候直接调用这个地方的代码就可以了 函数作用: 代码重用 函数的参数: 形参:函数定义的时候,函数名字后面的小括号里的变量 实参:函数调用的时候,函数名 ...
- 致Python初学者,Python常用的基础函数你知道有哪些吗?
Python基础函数: print()函数:打印字符串 raw_input()函数:从用户键盘捕获字符 len()函数:计算字符长度 format(12.3654,'6.2f'/'0.3%')函数:实 ...
- Python新手入门基础
认识 Python 人生苦短,我用 Python -- Life is short, you need Python 目标 Python 的起源 为什么要用 Python? Python 的特点 Py ...
- 4、java变量、函数、基本类型的值传递、分支、循环、流程控制
一.全局变量(global).局部变量(local).动态变量(dynamic).静态变量(static) 在类中的变量为全局变量,在方法函数中为局部变量,局部变量必须有人为赋的初值,全局变量的初值是 ...
随机推荐
- 【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 ...
- [问题记录]libpomelo的安装
1. 描述: 按照github上的操作完成 Windows in your libpomelo project root directory open git bash and type in mkd ...
- myeclipse 复制项目不包含svn或CVS目录
目前只记录到2个方法:(SVN和CVS都适用) 方法一:导出法 1.右击需要cp的目录,点击export,General/File System 2.next 3.确认你选择的目录,并勾选:Creat ...
- IOS AFN (第三方请求)
什么是AFN全称是AFNetworking,是对NSURLConnection.NSURLSession的一层封装虽然运行效率没有ASI高,但是使用比ASI简单在iOS开发中,使用比较广泛 AFN的g ...
- jmeter报告优化---展示详细信息
参考文档:https://www.cnblogs.com/puresoul/p/5049433.html 楼上博主写的还是很详细,在报告优化这块,但是在操作中也走了一些弯路,我改动了两个点才成功,根据 ...
- bzoj2331 [SCOI2011]地板
Description lxhgww的小名叫“小L”,这是因为他总是很喜欢L型的东西.小L家的客厅是一个的矩形,现在他想用L型的地板来铺满整个客厅,客厅里有些位置有柱子,不能铺地板.现在小L想知道,用 ...
- 两个List中的补集
/** * 获取两个List的不同元素 * @param list1 * @param list2 * @return */ private static List getDiffrent(List ...
- select下拉框之默认选项清空
最近和小伙伴发现,select默认选项一般是提示信息,怎么才能让当我们点击下拉框时,可选的选项中没有默认的提示信息呢? 思路: 1.当点击下拉框时,让默认提示信息,即下拉框第一个选项移除. 2.当没有 ...
- js 实现图片无限横向滚动效果
门户网站好多都有产品无线滚动展现的效果: 测试demo1 -- 非无缝滚动(可以看出来从头开始的效果): css样式如下: .box{ width: 1000px; border: 1px solid ...
- 【luogu P1351 联合权值】 题解
题目链接:https://www.luogu.org/problemnew/show/P1351 做了些提高组的题,不得不说虽然NOIP考察的知识点虽然基本上都学过,但是做起题来还是需要动脑子的. 题 ...