day6: functions and function parameters

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43264177/article/details/102672831

Third, functions and function parameters
question: What is the function? Function What is the role?
Question two: What have tasted the built-in function? What are the role?

(1) print: Output
(2) input: Input
(3) type: View data type
(4) id: acquiring data memory address
(5) range: generating data
(6) len: acquiring data length
(7) int, float, bool, str, tuple, dict, set: on behalf of the corresponding data type
question three: how to define a function?

# @time:2019/10/21 21:59
# @Author:coco
# @File:03函数 关键字 方法区分.py
# @software:PyCharm
"""
# 函数
函数使用是:函数名(参数)
print('hello python')
input("账号")

# 关键字
关键字使用:关键字名 python表达式
del li[0]
if 条件语句

# 方法
方法的使用:对象.方法名(参数)
li=[11,22,,33]
li.append()
"""

First, the definition and the calling function
1, function definition
(1) Defined Function keyword: DEF
(2) Why do you want to define a function: easy to use, reusability strong
(3) syntax:

def 函数名()#函数内部代码
# @time:2019/10/21 22:04
# @Author:coco
# @File:04函数的定义.py
# @software:PyCharm

"""
函数的定义
关键字:def

语法规则
def 函数名():
    # 函数体

为什么要函数?
    1.做功能封装,将一个功能的逻辑代码封装到一个函数中
    2.方便使用

"""

# 打印三角形封装一个函数,当num=1和3时打印出一个三角形
def func():
    for i in range(5):
        for j in range(i + 1):
            print("*", end=' ')  # print输出不换行,用end=''
        print(' ')

num=int(input("请输入数字:"))
if num ==1:
    func()
elif num == 3:
    func()

Print Results:
Here Insert Picture Description
call function 2: Function Name ()
Second, the function return values: return
action 1.return of:
(1) returns the number of values = 0: return None
(2) returns the number of values = 1: Back Object
( 3) returns the number of values> 1: return tuple
2. question: why use a return? When a return
as required, when the need to return to return, no return time would not have returned.
Precautions:
(. 1) is used to return results to the return function.
(2) when the function is executed to return the end of the function execution.
(3) a function is undefined return, the return value is the default None.

# @time:2019/10/23 5:46
# @Author:coco
# @File:05函数的返回值.py
# @software:PyCharm

s = "abc"
# res接收的就是id这个函数的返回值
res = id(s)
print('---------res输出结果----------')
print(res)

# 函数调用之后,返回的是None就代表瀚海样没有返回值
res2 = print('123')
print('---------res2输出结果----------')
print(res2)

res3 = type(s)
print('---------res3输出结果----------')
print(res3)  #有返回值,res3用来查看数据类型的

# s1接收的是字符串调用替换方法 之后返回的内容
s1 = s.replace('a','x')
print('---------s1输出结果----------')
print(s1)

# 列表里面很多都没有返回值
li=[11,2,33]
res4 = li.append(44)
print(res4)

# 函数中return 关键字 决定函数有没有返回值以及函数返回的内容
# return:这个关键字只能在函数里面用
# 作用:1.返回结果(函数的返回值)2.结束函数的运行(只要执行到一个return,这个函数就结束运行了)

def add_number():
    a = 100
    b = 200
    return a+b

res5 = add_number()
print('---------res5输出结果----------')
print(res5)

# 调用函数返回的内容由return关键字决定,return关键字后面写什么就写什么,
# 调用add_number1后,return后面写10000,就返回10000,所以res6的结果是10000,写abc就返回abc
def add_number1():
    c = 100
    d = 200
    return 'abc'

res6 = add_number1()
print('---------res6输出结果----------')
print(res6)

# 没有return返回值,就返回None(或者return后面什么都不写也返回None)
def add_number2():
    c = 100
    d = 200

res7 = add_number2()
print('---------res7输出结果----------')
print(res7)

# 结束函数的运行(只要执行到一个return,这个函数就结束运行了)
# return是返回内容,不会在控制台显示,print是接收return的内容,打印输出结果
# 一个函数里可以写多个return,但只要执行了第一个return,这个函数就终止运行了
def func3():
    li1 = [11,22,33]
    for i in li1:
        if i == 22:
            return '找到了22' #找到了22,就终止了函数,后面就不会再走了,所以后面的‘----’没有打印出来
        elif i == 33:
            return '找到了33' # 这个return不会执行,因为前面已经找到了22,已经执行了return
    print('---------')

res8 = func3()  # func3返回的就是return的值
print('---------res8输出结果----------')
print(res8)

Print Results:
Here Insert Picture Description
three, function parameters
1. Definition of parameters: Parameters practice parentheses after the function name
2. The transmission parameters:
two forms (1) Parameter passed:
positional parameters: positional parameters (carried by transfer position)
Keyword parameters: The keyword specifies a parameter passed.
Note: The key parameters written after the parameter position.
3. Define the parameters known as: parameter
actual transfer 4. Call for: argument
Here Insert Picture Descriptionthus achieving versatility we just say, just the teacher to the formal parameters, arguments, what is the argument? What is the parameter it?
1. parentheses define parameters for reception, called "parameter"
parameter parentheses 2. invocation, to be passed to a function called "argument"

# @time:2019/10/23 6:30
# @Author:coco
# @File:06函数的参数.py
# @software:PyCharm
"""
函数的参数:
定义:定义在名后面的括号中

形参:给函数定义的参数中做形参
形参分类:
    1.必备参数(必需参数),不能多传,也不能少传
    2.默认参数:在定义的时候可以设置默认值,调用的时候可以传
    3.不定长参数:不限定长度的参数,可以传0个,也可以传任意一个,传进来用元组接收,定义参数的时候,顺序不能修改
        *args:用来接收不定长位置传参
        **kwargs:用来接收不定长度的关键字传参,不传是空字典

实参:调用函数的时候,给参数调用的内容
    1.按位置传递(位置传参),按参数定义的位置一一对应进行传递
    2.通过参数名指定传递(关键字传参),传递参数的时候不要考虑参数的位置

"""

First, the essential parameters

# 必备参数
def func(a,b,c):
    print('a:',a)
    print('b:',b)
    print('c:',c)

func(11,22,33) # 1.这个就叫做必备参数,定义了必须要传输,多传和少传都会报错
               # 2.这个是实参,按位置传,第一个传给第一个,第二个传给第二个,第三个传给第三个

Print Results:
Here Insert Picture Description
What if I want to define a function of three numbers together then, how do you define it? It is not necessary to use three parameter

def addition_2(a,b,c):
	d = a + b + c
	print(d)

那么调用函数的时候我们需要输入几个参数呢?
我们先来试一下两个参数看行不行?

addition_1(11,22)
# 运行结果:报错

为什么会报错呢?因为我们在定义函数的时候声明了需要三个参数,调用的数量必须和声明的一样,而且传入的位置和定义的位置顺序是一致的,这种叫做必备参数。

addition_1(11,22,33)

参数在传入的时候还可以指定名称,指定名称的参数可以不按顺序写;

addition_1(b = 11,c = 22,a = 33)

指定名称的参数我们叫做命名参数

# 实现两个数相加的函数
def add_number(a,b):
    return a+b

# 定义了参数的函数,调用的时候就需要传递参数
res1 = add_number(100,300)
print(res1)

打印结果:
Here Insert Picture Description

二、默认参数(缺省参数)
当然有必备参数,那么函数中还有一种不是必须要传入的参数,叫做缺省参数,也可以称之为默认参数,什么样的一个形式呢,大家跟我来看一下:

def student_info(name,age,course = python):
	print("名字",name)
	print("年龄",age)
	print("学科",course)

调用函数时,默认参数(缺省参数)的值如果没有传入,则是被认为是默认值

student_info("小王",18)
# 运行结果
名字:小王
年龄:18
学科:python

调用函数时,如果传入了参数,则用传入的参数

student_info("小王",19,"java")
# 运行结果
名字:小王
年龄:19
学科:java

注意:带有默认值的参数一定要位于参数列表最后面

def student_info(name,course = python,age):
	print("名字",name)
	print("年龄",age)
	print("学科",course)
# 默认参数
def func1(a,b,c=99):
    print('a:', a)
    print('b:', b)
    print('c:', c)

func1(a=99,b=88,c=999) # 指定参数名传给谁,第一个传给99给a,第二个传88给b第三个传统999给c
# func1(a=99, c=999,b=88 )  # 按位置传,丝毫没有影响,随便写,不用考虑参数的位置

打印结果:
Here Insert Picture Description

三、不定长参数
接下来给大家介绍不定长参数,有时候可能需要一个函数能处理比当初声明更多的参数。这些参数,声明时不会命名。

def func_argument(a,b,*args):
	"""不定长参数演示"""
	print(a)
	print(b)
	print(args)
	func_argument(11,22,33,44,55)
	# 运行结果:
	11
	22334455

大家刚刚看到我在变量中写了个“ * ”号,那么这个 “ * ”号有什么功能呢?
我们来运行一下刚刚写好的代码,打印出来的结果,这里怎么多了个元组呢?我们打印出来的“args”的结果是一个元组,有点意思,元组里面的元素就是我们刚刚多传进去的几个参数,这就是我们所说的不定长参数。
大家注意听,重点来了,在我们定义函数的时候,给某个参数加上一个
”,那么这参数就叫做不定长参数,它可以接收所有未被其他参数接收所以未命名参数,并且以一个元组的形式保存。
那么关于不定长参数,还有一个加两个“ ** ”的,来看一下加两个 “ ** ”有什么功能?

def func_argument(a,b,*args,**kwargs):
"""不定长参数演示"""
	print(a)
	print(b)
# 不定长参数
def func2(a,b,c=99,*args):
    print('a:', a)
    print('b:', b)
    print('c:', c)
    print("*args",args)

func2(55,66,77,88,99)

def func3(a,b,c=99,**kwargs):
    print('a:', a)
    print('b:', b)
    print('c:', c)
    print("kwargs",kwargs)

func3(c=55,a=66,b=77,d=88,e=99,f=888)

Print results:
Here Insert Picture Descriptionlike kwargs with two added a ** and there is no reaction, no results have not changed our name is transferred within a multi-parameter into account, but have not received a kwargs. Why is this? Do not worry, the problem with the teacher to follow.
We then pass a few parameters to the function named in look.

def func_argument2(a,b,*args,**kwargs):
	"""不定长参数演示"""
	print(a)
	print(b)
	print(args)
	print(kwargs)
func_argument(11,22,33,44,55,c = 888,d = 666)
# 运行结果
11
22334455"c":888,"d":666

There did not find anything to take on the operating results, are not we just pass in several parameters saved to kwargs inside in the form of a dictionary, now discovered this with two parameters ** No. role do
pay attention to listening, which is the a focus on
variable length parameters with ** are not accepted to receive all named arguments, and in the form of a dictionary, that is key = value key = worthy of preservation on the inside, since kwargs is a dictionary, we can also for kwargs circulating inside the key to traverse it.

def func_arugment(a,b,*args,**kwargs):
	"""不定长参数演示"""
	print(a)
	print(b)
	print(args)
	print(kwargs)
	for key value in kwargs:
		print(key,"=",value)
func_argument(11,22,33,44,55,c = 888,d = 666)
运行结果:
11
22334455"c":888,"d":666
c = 888
d = 666

This is the most complex transfer function parameters

Guess you like

Origin blog.csdn.net/weixin_43264177/article/details/102672831