Table of Contents
What is a function? ?
1. Function call
2. Define functions
#3. Function parameters
4. Function return value
5.变量作用域
Home Backend Development Python Tutorial Detailed explanation of python basic syntax functions

Detailed explanation of python basic syntax functions

Apr 24, 2022 pm 01:04 PM
python

This article brings you relevant knowledge about python, which mainly introduces related issues about functions, including function calls, defining functions, function parameters, function return values, and variable functions. Domains and other contents, let’s take a look at them below. I hope it will be helpful to everyone.

Detailed explanation of python basic syntax functions

Recommended learning: python video tutorial

What is a function? ?

A function is an organized, reusable code segment used to implement a single or related function. Functions can improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
In short, functions are used a lot in our daily life, but most of them are officially defined functions. We can call them directly, such as input(), print(), etc., but it We don't care how it is defined. If we need to reuse a complex code block in large quantities in our code, then we can define a function to represent this code block and call it directly when needed! !

1. Function call

A function consists of three parts: function name, parameters and return value.
The function name is the identifier of the function.
The parameters of the function are to provide data to the function when calling the function.

name = input("请输入你的姓名:")list  = len(name)print(list)
Copy after login

Detailed explanation of python basic syntax functions
Here, input, len, and print are the function names, the ones in the function brackets are the parameters, and the ones on the left side of the equal sign are the return values.
Calling a function: Generally add parentheses to the function name. Parameters can be filled in in parentheses to provide data for the function. Of course, some functions do not require parameters (list.clear()), and some functions must pass parameters (list.append()).

2. Define functions

You need to use the def (define) keyword to define a function and it must end with a colon.
The function must be defined first before calling

def name():
    print('苏凉')def QQ_num():
    print('787991021')def Total():
    name()
    QQ_num()
    Total()
Copy after login

Detailed explanation of python basic syntax functions

Define the function:
Function header: keyword def custom function name Add parentheses and end with a colon. def name(),def QQ_num(),def Total()
Function body: The function that needs to be implemented by the function. That is, the function body must be indented by 4 characters. A tab key.
Note: The execution of functions is from top to bottom, that is, the function must be defined first before calling.

#3. Function parameters

The parameters of the function can make the function we define more flexible.
Note: If parameters are passed in when defining the function, the parameters must also be specified when calling.

#When passing parameters, you can pass in one parameter or multiple parameters.

# 传入一个参数def list(len):
    print('+' * len)list(5)# 传多个参数def list2(num1 , num2):
    print(num2 * num1)list2('*',15)list2(5,10)
Copy after login

When calling a function, the actual value (actual parameter) is given, so that the defined parameter (formal parameter) will be assigned a value.

Detailed explanation of python basic syntax functions
Note: When passing in multiple parameters, you need to pay attention to whether the number and order of parameters are correct. Different functions have different meanings. .

4. Function return value

The function can return a single value or multiple values. Use return to return the value.
Note: When the function executes return, the function execution ends. That is, the function body after return will not be executed again.

def num(age,sex):
    if age200:
        return
    else:
        return age,sex

x = int(input('输入年龄:'))Sex = input('输入性别:')num ,sex  = num(x,Sex)print(num,sex)
Copy after login

Use as many values ​​as the function returns to receive, otherwise an error will be reported. In this case a single value is returned respectively.

Detailed explanation of python basic syntax functions

A special case is to use a variable to accept, and the returned value is a tuple type!

result = num(x,Sex)print(result)
Copy after login

Detailed explanation of python basic syntax functions
Summary: The function can return a single value or multiple values. When multiple values ​​are returned, multiple corresponding variables need to be used to receive the values ​​returned by the function. Value, if only one value is received, a tuple type value is returned.

5.变量作用域

变量的作用域:即是指在那个地方可以使用变量。这就涉及到了全局和局部两种变量。
全局(global)变量:在函数外定义的变量。无论在函数体内或者函数体外都可以使用! ?全局变量在函数体内只能使用而不能直接修改!!
局部(local)变量:在函数内定义的变量,在函数内定义的变量,只能在函数体内使用和修改,在函数外调用就无效了。 在函数内可以定义一个名字和函数外一样的变量,但他们的意义时不一样的!!


a = 15 #这里a为全局变量def num():
    a = 5 #这里a为局部变量,名字可以相同但代表不同的值
    print(a)num()print(a)
Copy after login

结果:
Detailed explanation of python basic syntax functions

这里可以看到局部变量是不能修改全局变量的值的。


a = 15 #这里a为全局变量def num():
    # 在函数体内可以使用全局变量
    print(a)
    num() #结果15print(a) #结果15
Copy after login

在函数体内是可以使用全局变量的


a = 15 #这里a为全局变量def num():
    global a  #定义全局变量
    a = 5
    print(a)num() #结果5print(a) #结果5
Copy after login

若想要在函数体内修改全局变量,则需在修改之前,定义全局变量,此时函数体内的变量a为全局变量,不再是函数体内定义的局部变量了。

推荐学习:python视频教程

The above is the detailed content of Detailed explanation of python basic syntax functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles