Python study notes Day 7 ‘function‘

本文详细介绍了Python中的函数概念,包括如何定义无参和带参函数,以及局部变量和全局变量的使用。通过实例展示了如何调用函数、传递参数,并解释了默认参数值和函数返回值的概念。此外,还讨论了在函数中如何访问和修改全局变量。
摘要由CSDN通过智能技术生成

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

Screen Shot 1

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.
Screen Shot 2

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.
Screen Shot 3

m = 5
n = 6
function2(m,n)
function2(n,m)

Or, we can also define a function by assigning default values to each parameter.
Screen Shot 4

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

Screen Shot 5

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

Screen Shot 6

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:
Screen Shot 7

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
Screen Shot 8

def add(a,b):
    c = a + b
    return c

n = add(1,2)
print(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值