Function in Python

Function is a bundle of expression and operations.

A function in Python makes up 3 parts:

|---------------|---------------------------------------------------------------------------------|
| Parameters | A function can receive any number of parameters |
| Function Body | The main structure of function. All the parameters will be process in the body. |
| Return value | the funciton body can process the data and then generate a return result. |

1. Grammar of Function

python 复制代码
def my_function():
    # do sth
    # return sth
  1. We use key worddef to define a function. (def is the abbreviation of define)

  2. the name of function is arbitrary. (in the instance, the name of function is my_function)

  3. the function body should be wrap in the indentation.

  4. you can return a variable or not , using return ... (e.g. return "hello")

Now see a concrete exemple:

python 复制代码
def add(a, b):
    return a + b

# The name of the function is add, meaning addition operation
# The function body contains a return statement
# the a + b will calculate the addition of a and b
# and then the result of a + b will be return

How to use function defined by ourselves?

python 复制代码
a = add(1, 5)
print(a)

# 1 and 5 will be pass to the function add as arguments and then be added
# the function return the addition of 1 and 5
# variable a receive the return value of add(1, 5), then a is 6 now
# print() is also a build-in function, which can output the value of a on the screen

2. Details

Understanding the nature of function requires you to know following points:

2.1 When variables are passed to a function as arguments, the interpreter does2things:

  • copy the references of the variables
  • pass the copies of the variables to the function

As you can see, in the instance

复制代码
a = 1
b = 2

add(a, b)
  • a is a reference pointing to a space in the memory storing 1 , and b points to the other storing 2 as well.
  • Then the interpreter copy the reference a and b and create their copies . We just call them a1 and b1 . Then a1 and b1 are passed to the function.

2.2 When the function return a variable(such as return a + b), the interpreter only return the reference of the variable.

  • In the instance above, the value of a + b will be stored in a temporary variable and then the function will return the reference of the variable.

    original:
    a ----> 1
    b ----> 2

    copy:
    a, a1 ----> 1
    b, b1 ----> 2

    pass:
    add(a1, b1)

    operate:
    a1 + b1 ----> 3

    return:
    c, a1 + b1 ----> 3
    return c

3. Scope of value

3.1 local and global variable

A scope of variable is the action scope of the variable. A variable defined in a for loop , while loop , if...else statement or function is a local variable , which CANNOT be accessed outside the block. In the following examples, you can see the limitation of a local variable.

python 复制代码
for i in range(0, 5):
    print(i)

print(i) # error, i is a local variable belonging to the for loop

============================================================================

if(1==1):
    a = "hello"
    print(a)

print(a) # error, i is a local variable belonging to the if...else block

============================================================================

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

print(c) # error, c is a local variable belonging to the function add

============================================================================

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

def get():
    print(c) # error, c is a local variable belonging to the function add

The concept on the opposite side of local variable isglobal variable . If a variable is not defined in any loop , if...else block or function , the variable will become a global variable , which can be accessed in the loop , if...else block.

python 复制代码
a = 1

for i in range(0,5):
    print(a)             #yes
    a = a + 1            #yes

if(1==1):
    print(a)             # yes
    a = a + 1            # yes

However , in a function, the condition is a little bit different. So we must introduce the concept of the scope of variable.

3.2 Scope of variable

A function will create a scope of variable. A variable in a scope can read the value of global variable but CANNOT change it.

python 复制代码
var = 1

def add(a, b):
    print(var)      # yes
    var = a + b     # error

If you want to change the value of a global variable, use keyword global

python 复制代码
var = 1

def add(a, b):
    global var      # now you can use the var
    print(var)      # yes
    var = a + b     # yes

add(1, 2)
print(var)  # output 3

Note that if the parameters of a function has the same name of a global variable, the interpreter will give priority to using local variable.

python 复制代码
a = 1

def add(a, b):
    return a + b     # the a here is the argument

add(2 ,4)   # return 6

Note that a loop or if...else statement won't create a scope of variable

相关推荐
linweidong38 分钟前
中科闻歌Java面试题及参考答案
java·python·大模型·提示词·ai agent·mcp·rag原理
小玮看世界1 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法
萧鼎1 小时前
2026实战:用 tomlkit 优雅读写 TOML 配置,告别手写解析器
python·开源·教程·python库
小刘在重生~2 小时前
Java 常用类|包装类 装箱拆箱、Integer 缓存面试题
java·python·缓存
2601_962099462 小时前
Python xlwt设置excel单元格字体及格式
python·excel·xlwt·样式设置·单元格格式
奇牙coding1232 小时前
GPT-6-Astra API 接入教程:OpenRouter 路由配置 + Python/curl 示例 + 静默降级踩坑
开发语言·python·gpt·ai
2601_962298273 小时前
Python与Selenium结合的Web自动化测试全流程实践教程
自动化测试·python·selenium·web测试·pageobjectmodel
天衍四九-3 小时前
第一章:从 LLM 到 Agent —— DeepSeek Harness 入门
网络·数据库·人工智能·python
529宝宝起名网3 小时前
用 Python 实现名字寓意评分算法:基于 NLP 语义分析的名字内涵深度评估
python·算法·自然语言处理
2601_962298673 小时前
Python:对象缓存优化机制(CPython)
python·性能优化·内存优化·cpython·对象缓存