Functions in python3

本文介绍了Python3中函数的概念和用法,包括定义函数、调用函数、参数类型如必填参数、关键字参数、默认参数和可变长度参数。特别强调了在使用可变长度参数时应注意的事项,以及如何传递字典作为命名参数。
摘要由CSDN通过智能技术生成

A function is a block of orgnized, reusable code that is used to perform a single ,related action.Fuctions provide better modularity for your applications and a high degree of reusing.

Definition of a function
def func(self):
	print("This's a function trial.")
	return 'This is the returing things.'
  • Line 1 use define a function named func,with only one parameter called self(self is always used in a inner class function.).
  • Line2 write out what the function does, this is how the function works.
  • And line 3 with the return [expression] to tell the computer we are going to exit the function, and the value after return is what the function passing back to the caller. Actually, you can write nothing here after the return word, then it will pass back the value None (something equal to 0 sometimes).
  • Eventually, u can finish the function without a return expression, it will work sometime, but it will cause a bugger when u try to call this function in the other time, for instant if you want to use the value pass from the funtion.
Calliing a function

Once you have defined a function, you can call it with typing its’ name anytime, anywhere in the same code files, it’s easy. But there’re also several rules you should obey.

  1. Required arguments are the arguments passed to a function in correct positional order. That is to say, if you want to call a function correctly, you have to pass through all the arguments in an exactly right consequence. Here is an example:

    def func(name, age, weight, height):
    	print(f'{name} is {age} years old, {height} high and {weight} pounds.')
    	return
    	
    func('Alice', 18, 80, 170)
    
  2. Keyword arguments. If you do not like to pass through all the arguments in the default consequence, then will can use the keyword argument. In this way, the caller will identify the arguments by the parameter names.

    def func(name, age, weight, height):
    	print(f'{name} is {age} years old, {height} high and {weight} pounds.')
    	return
    	
    func(name = 'Alice', weight = 80, height = 170, age = 20)
    
  3. Default arguments. If an argument has been set a default value when you are difining the function, then you can pass nothing to it if you don’t want to do that when you’re calling the function. In the case, the value of this default argument is equal to the default value.

    def func(name, age = 20):
        print(f"{name} is {age} years old")
        return
    
    func('Ash', 33)
    func("Ash")
    
  4. variable-length arguments. A variable length argument, means the length of this argument can be changed, we always write it in the pression *args, you can also write in some other words with *, like *first, but you’ld best write it as *args.

    def func(x, *arg):
        larger = x
        print(arg)
        for i in arg:
            if i >= larger:
                larger = i
            else:
                print(f"{larger} isn't changed this turn.")
        return larger
    
    print(func(3,67,5,38,9,68))
    tup = (4,6,56,7,45,3)
    print(func(tup))
    

    Here’s the output:

    (67, 5, 38, 9, 68)
    67 isn't changed this turn.
    67 isn't changed this turn.
    67 isn't changed this turn.
    68
    ()
    (4, 6, 56, 7, 45, 3)
    

    In this example, we can easily get a result, that *args is regarded as a tuple, but when you pass values to this argument, it’s not right to just use a tuple as one argument. The correct way is to take all this values as arguments passing to *args.

    And also, if you have some other parameters difined in the function, it should be laid before the *args, so that when you pass values to arguments, the other parameters will take those values one by one, and leave other values for *args, no matter how much it is.

  5. Using many named argument with **kwargs. It works just like an *args, but stores a dictionary in stead of a tuple.

    def func(**kwargs):
        return kwargs
    print(func(a  = 55))
    print(func(x  = 39, jack = 'son of luci'))
    
    {'a': 55}
    {'x': 39, 'jack': 'son of luci'}
    

    Tips:

    • when you use this to pass a dictionary to the arguments, don’t use a packaged dictionary, instead, you should use it without {}.
    • When you difine a dictionary, the key should be something which can not be changed, such as string(‘a’), int( 55), or a tuple. But for this argument, no more ’ ’ needed for the key word.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值