zoukankan      html  css  js  c++  java
  • python函数解释

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

    return 的作用:
    1、把函数处理的结果返回
    2、结束函数,函数里面遇到return,函数立即结束

    详情: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
    '写入'a.txt'里
    write_file('a.txt','123
    ') #实参:实际参数
    # 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里面的内容
    #return返回的结果可用,print不行
    def func(a,b):
        res=a+b
        print(res)#只能看结果,但不能用
    
    def func2(a,b):
        res=a+b
        return res #可以用
    
    def get_user():
        s='abc,123'
        username,password=s.split(',')
        return username,password #可被其他函数调用,可return多个值用逗号分开,可用一个变量来接收
    
    res=get_user()
    print(res)# 可用一个变量来接收 ('abc', '123')
    
    def login():
        for i in range(3):
            username,password=get_user()
            user=input('username:')
            pwd=input('password:')
            if username==user and password==pwd:
                print("登录成功")
                return
            else:
                print("账号密码错误")
  • 相关阅读:
    spark
    mongdb
    redis
    mysql
    kylin
    kafka
    hadoop+hive+hbase+kylin
    git
    elasticsearch
    clickhouse
  • 原文地址:https://www.cnblogs.com/denise1108/p/10021933.html
Copyright © 2011-2022 走看看