python函数解释

实现某个功能的一些代码
提高代码的复用性
函数必须被调用才会执行
函数里面定义的变量都叫局部变量,只要一出了函数就不能用了
函数里面如果调用时需要拿到结果但是最后没写return(不必须写,如读取文件时就需要),则返回None
函数得先定义后使用,使用时注意先后顺序

详情:http://www.runoob.com/python3/python3-function.html

# 1. 定义一个可输出hello world的函数
def hello(): # 定义函数用def
    print('hello world')
    
#调用函数1
hello() #调用函数,输出hello world


# 2. 定义一个将content写入file的函数
def write_file(file_name,content): #入参,不必须写,根据需求
    # 形参:形式参数
    with open(file_name,'a+',encoding="utf-8") as fw:
        fw.write(content)
    # print(file_name,content)  #以上代码为函数体
        
#调用函数2,将'123\n'写入'a.txt'里
write_file('a.txt','123\n') #实参:实际参数
# write_file('b.txt','456')
# write_file('c.txt','789')


# 3. 定义一个可读取并输出file里的content的函数
def read_file(file_name):
    with open(file_name, 'a+', encoding="utf-8") as fw:
        fw.seek(0)
        content = fw.read()
        return content
    
#调用函数3
res = read_file('a.txt')
print(res)  #输出a.txt里面的内容

猜你喜欢

转载自www.cnblogs.com/denise1108/p/10021933.html