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:UsersxiajinqiPycharmProjects	wodayvenvScriptspython.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 
" %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:UsersxiajinqiPycharmProjects wodayvenvScriptspython.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':'222'}

_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,*["100","200",'300'])
_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:UsersxiajinqiPycharmProjects	wodayvenvScriptspython.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 = '1'
    with open(file_name, "a+", encoding="utf-8")  as  f:
        for line in f:
            if line.strip() == "backend %s" % (domain_name):
                result = "0" #表示已经存在0
                break
        if result != '0' :
            print("不存在添加")
            f.write("backend %s
" %(domain_name))
            for ip in list['server']  :
                f.write("		 server %s weight %s maxconn %s
" %(ip,list['ip_weight'],list['ip_maxconn']))
            result = '1'
    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 == '1' :
        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 == '2' :
        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 == '0' :
            print("输入的域名已经存在,请重新输入")
        else :
            print("添加成功")

    elif  user_choice == '3' :
        domain_name = input("请输入你要删除的域名:")
        del_result = file_del(domain_name)
        if del_result == 0 :
            print("删除成功",del_result)
        else :
            print("失败",del_result)

    elif  user_choice == '4' :
        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 == '0' :
            print("更新域名不存在")
        else:
            print("更新成功")

    elif user_choice == '5':
        print("退出登录")
        exit()
    else :
        print("输入错误")
        continue
良禽择木而栖 贤臣择主而侍
原文地址:https://www.cnblogs.com/xiajq/p/8734036.html