Python study notes Day 7 ‘function’
Today’s topic is about the function.
This is an extremely important part in the world of computer programming.
We can define a function by naming it and describe it in detail within the structure defined.
def function():
The contents of the function
function()#The function is called

def function1():
a = 1
b = 2
c = a + b
print(a)
print(b)
print(c)
function1()
Or, we can define functions with parameters.
Parameters are local variables that have the property of acting only inside the function.

def function2(a,b):
c = a + b
print(a)
print(b)
print(c)
function2(3,4)
In the picture, ‘a’ and ‘b’ are parameters and when we call a function, we assign values to both parameters.
Or, we can define and assign two global variables, and then assign the two global variables to the two parameters when the function is called.

m = 5
n = 6
function2(m,n)
function2(n,m)
Or, we can also define a function by assigning default values to each parameter.

def function3(a=7,b=8):
c = a + b
print(a)
print(b)
print(c)
function3()

a = 1
b = 2
def function3(a=7,b=8):
c = a + b
print(a)
print(b)
print(c)
function3()

def function3(a=7,b=8):
c = a + b
print(a)
print(b)
print(c)
function3(9)
function3(9,10)
When we want to use global variables in a function:

a = 11
def function3(b=8):
global a
c = a + b
print(a)
print(b)
print(c)
function3()
Sets the return value of the functionL

def add(a,b):
c = a + b
return c
n = add(1,2)
print(n)
本文详细介绍了Python中的函数概念,包括如何定义无参和带参函数,以及局部变量和全局变量的使用。通过实例展示了如何调用函数、传递参数,并解释了默认参数值和函数返回值的概念。此外,还讨论了在函数中如何访问和修改全局变量。
1097

被折叠的 条评论
为什么被折叠?



