Logo
Section 1 / 13

定义和调用函数

使用 def 关键字定义可重用的代码块,通过参数传递数据,并使用返回值捕获结果。

导入

定义和调用函数

使用 def 关键字定义可重用的代码块,通过参数传递数据,并使用返回值捕获结果。

1def <function_name>(): 2 # Function's body
1def welcome_message(): 2 """Prints a standard welcome message.""" 3 print("Welcome to the System.") 4 print("Initializing modules...") 5 6# The function is defined above, but runs here 7welcome_message()
1def create_greeting(name): 2 """Generates a personalized greeting.""" 3 message = f"Hello, {name}! We are glad you're here." 4 print(message) 5 6# Calling the function with different arguments 7create_greeting("Alex") 8create_greeting("Taylor")
1def calculate_area(length, width): 2 """Calculates the area of a rectangle and returns the result.""" 3 area = length * width 4 return area 5 6# 1. Call the function and store the returned result in a variable 7pool_area = calculate_area(length=10, width=5) 8 9# 2. Use the result in another calculation 10tile_cost = pool_area * 15 11 12print(f"Pool Area: {pool_area} sq meters") 13print(f"Total tile cost: ${tile_cost}")
1def process_data(): 2 result = 20 # Defined inside the function 3 return result 4 5final_output = process_data() 6print(final_output) 7 8# ERROR: 'result' does not exist here! 9print(result)

对象关系与数据模型

变量作用域与生命周期