Python 入门(第10部分):使用函数

发布: (2025年12月23日 GMT+8 21:09)
3 min read
原文: Dev.to

Source: Dev.to

使用函数

在本文中,你将学习 函数。通过使用函数,你可以复用特定的过程,编写更简洁、更易维护的代码。

你可以使用 def 语句来定义函数。定义函数后,必须 调用(执行) 它才能运行其中的代码。

def function_name():
    """Function description"""
    process

# Call the function
function_name()

示例

# Define a function
def say_hello():
    """A function that prints a greeting"""
    print("Hello, Python!!")

# Call the function
say_hello()  # Hello, Python!!

# A defined function can be called as many times as you like
say_hello()  # Hello, Python!!
say_hello()  # Hello, Python!!
say_hello()  # Hello, Python!!

使用参数

通过使用 参数,你可以创建更灵活的函数。

def function_name(argument):
    """Function description"""
    process

示例

# Define a function with one argument
def say_hello(lang):
    """A function that greets in a chosen language"""
    print("Hello, " + lang + "!!")

# Call the function
say_hello("Python")   # Hello, Python!!
say_hello("Rust")     # Hello, Rust!!
say_hello("Kotlin")   # Hello, Kotlin!!
say_hello("Swift")    # Hello, Swift!!

使用多个参数

你可以根据需要定义任意数量的参数。

def function_name(arg1, arg2, arg3, ...):
    """Function description"""
    process

示例

# Define a function with two arguments
def say_hello(greet, lang):
    """A function that combines a greeting with a language"""
    print(greet + ", " + lang + "!!")

# Call the function
say_hello("Hello", "Python")          # Hello, Python!!
say_hello("Ciao", "C/C++")            # Ciao, C/C++!!
say_hello("Bonjour", "Java")          # Bonjour, Java!!
say_hello("Namaste", "JavaScript")    # Namaste, JavaScript!!

使用返回值

通过使用 return,函数可以执行一些处理并 将结果返回 给调用者。如果函数没有使用 return,则默认返回 None

def function_name(arg1, arg2, arg3, ...):
    """Function description"""
    process
    return result

示例 – 将数字翻倍

def calc_double(num):
    """A function that returns double the value"""
    return num * 2

print(calc_double(10))  # 20
print(calc_double(20))  # 40
print(calc_double(30))  # 60

示例 – 两数相加

def calc_total(num1, num2):
    """A function that returns the sum of two numbers"""
    return num1 + num2

print(calc_total(10, 20))  # 30
print(calc_total(30, 40))  # 70
print(calc_total(50, 60))  # 110

参数和返回值常常一起使用,所以请确保你对这两个概念都有深入的理解。

接下来会学什么?

感谢阅读!在下一篇文章中,我们将学习 模块

“Getting Started with Python (Part 8): Using Modules”

敬请期待! 🚀

Back to Blog

相关文章

阅读更多 »

Swift #12:函数

函数是由大括号 { 包围并以名称标识的代码块。不同于在循环和条件中使用的代码块……

JavaScript 中 Function 的核心前提

这算是 JavaScript 中的函数吗?javascript function fiveSquared { return 5 5; } 从技术上讲,是的。然而,fiveSquared 缺乏真实场景中所需的可复用性……