def greet(name):
"""Greets the user with their name."""
print(f"Hello, {name}!")
greet("Ram")
greet("Shyam")
编辑器中的此代码定义了一个采用 name 参数的 greet 函数。然后,该函数根据 name 参数值向用户打印个性化问候语。然后,代码执行两次 greet 函数,一次使用名称“Ram”,一次使用名称“Shyam”。
输出
Hello, Ram!
Hello, Shyam!
创建函数
创建函数的语法
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
调用函数
调用函数的示例
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return;
# Now you can call printme function
printme("I am the first call to a user-defined function!")
printme("Again a second call to the same function")
“”函数,用于打印提供给它的字符串,在此 脚本中定义。它演示了在两次调用此过程时如何使用两个单独的字符串参数。
输出
I am the first call to a user-defined function!
Again a second call to the same function
中的 Pass by Value 和 Pass by 中的按值传递
中的传递值示例
student = {'Ram': 12, 'Rahul': 14, 'Rajan': 10}
def test(student):
student = {'Shyam':20, 'Shivam':21}
print("Inside the function", student)
return
test(student)
print("Outside the function:", student)
此 代码创建一个名为“”的字典,其中包含几个键值对,然后调用名为“test”的函数,该函数将“”字典传输到其他字典。在函数内部打印时会出现新词典,但由于在函数外部打印时函数所做的修改是本地的,因此会出现旧的“”词典。
在 中按引用传递
中的引用传递示例
student = {'Ram': 12, 'Rahul': 14, 'Rajan': 10}
def test(student):
new = {'Shyam':20, 'Shivam':21}
student.update(new)
print("Inside the function", student)
return
test(student)
print("Outside the function:", student)
这个 程序定义了一个名为“”的字典和一个名为“test”的函数,该函数通过从函数的“new”字典中添加新的键值对来更新名为“”的字典。“”字典反映了函数在函数内部和外部执行的调整。
参数
默认情况下python高阶函数,必须始终使用适当数量的参数调用函数。换句话说,如果函数需要 2 个参数,则必须使用 2 个参数调用它,而不是更多或更少。如果尝试仅使用一个或三个参数调用函数,则会发生错误。
任意参数,*args
中的任意参数示例
def sum_numbers(*args):
total = 0
for num in args:
if not isinstance(num, (int, float)):
raise TypeError(f"Expected a number, got {num}")
total += num
return total
# Example usage:
result = sum_numbers(1, 2, 3, 4, 5)
print("Sum:", result)
此示例中的 函数接受任意数量的输入,并使用 中的 for 循环将它们全部相加。当您调用 (1python高阶函数, 2, 3, 4, 5) 时,将计算、返回这些数字的总和并报告给控制台。您可以自由地传递任意数量的论点;它们都将被收集到函数的 args 元组中。
输出
Sum: 15
关键字参数
中的关键字参数示例
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
# Using keyword arguments to call the function
greet(name="Alice", age=30)
greet(age=25, name="Bob")
Name 和 age 是此示例中的 greet 函数接受的两个参数。在调用函数时,我们使用关键字参数来定义这些参数。函数定义中定义的参数不需要按照与参数相同的顺序传递给它。
输出
Hello, Alice! You are 30 years old.
Hello, Bob! You are 25 years old.
任意关键字参数,**
中的任意关键字参数示例
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Example usage
print_kwargs(name="Alice", age=30, city="New York")
此示例中的 方法使用 ** 接受任何关键字参数。当使用参数 name=“Alice”、“age=”30“ 和 city=”New York“ 调用函数时,将创建一个字典 。然后,该函数在字典中输出每个键值对。
name: Alice
age: 30
city: New York
函数参数
中的函数参数示例
# Function with positional arguments
def add_numbers(a, b):
result = a + b
return result
# Calling the function with positional arguments
sum_result = add_numbers(3, 5)
print("Sum:", sum_result)
# Function with keyword arguments
def greet_person(first_name, last_name):
greeting = f"Hello, {first_name} {last_name}!"
return greeting
# Calling the function with keyword arguments
greeting_message = greet_person(first_name="John", last_name="Doe")
print(greeting_message)
该代码定义了两个函数:“”接受两个位置参数并返回它们的总和,“”接受两个关键字参数并提供问候语。使用某些参数,将调用函数并报告输出。
输出
Sum: 8
Hello, John Doe!
中的必需参数
中必需参数的示例
def add_numbers(a, b):
result = a + b
return result
# Call the function with required arguments
sum_result = add_numbers(5, 3)
print("Sum:", sum_result)
此示例使用 函数,该函数需要两个输入 a 和 b。调用此函数时,a 和 b 都必须具有值。我们在 (5, 3) 调用中将 5 作为 a 传递,将 3 作为 b 传递。然后返回函数将这两个数字相加的结果并报告给控制台。
输出
Sum: 8
默认参数值
中默认参数值的示例
def greet(name="Guest"):
print(f"Hello, {name}!")
# Calling the function with and without an argument
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
在此示例中,在 编译器中,greet 函数的默认参数值的 name 参数设置为“Guest”。该函数在没有参数的情况下调用时使用默认值。如果提供参数,则该参数将替换提供的值。
输出
Hello, Guest!
Hello, Alice!
中的默认参数
中的默认参数示例
def greet(name, greeting="Hello"):
"""Greet a person with a default greeting."""
print(f"{greeting}, {name}!")
# Calling the function without providing a custom greeting
greet("Alice") # Output: Hello, Alice!
# Calling the function with a custom greeting
greet("Bob", "Hi") # Output: Hi, Bob!
在此示例中,Name 和 是 greet 函数的两个参数。 参数的默认值为“Hello”。当调用函数而没有问候值时,将使用默认值。但是,在使用该函数时,可以通过传递特定的问候语来覆盖默认值。
输出
Hello, Alice!
Hi, Bob!
中的可变长度参数
编译器中的可变长度参数示例
# Define a function that accepts a variable number of arguments
def add_numbers(*args):
result = 0
for num in args:
result += num
return result
# Call the function with different numbers of arguments
sum1 = add_numbers(1, 2, 3)
sum2 = add_numbers(10, 20, 30, 40, 50)
# Print the results
print("Sum 1:", sum1) # Output: Sum 1: 6
print("Sum 2:", sum2) # Output: Sum 2: 150
此示例中的 函数使用 *args 接受可变数量的参数。然后,在遍历每个参数后计算参数的总和。可以使用任意数量的输入调用此函数,并且它将适当地计算总和。
输出
Sum 1: 6
Sum 2: 150
递归
中的递归示例
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Test the factorial function
num = 5
result = factorial(num)
print(f"The factorial of {num} is {result}")
这个 程序首先构建递归函数“(n)”,它计算非负整数“n”的阶乘,然后通过计算和打印 5 的阶乘来测试它。
输出
The factorial of 5 is 120
中的匿名函数 中匿名函数的语法
lambda [arg1 [,arg2,.....argn]]:expression
中的匿名函数示例
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
编辑器中的这个程序定义了 函数 “sum”,它接受两个参数并返回这些参数的总和。它解释了如何使用 函数分别计算和显示 10 和 20 以及 20 和 20 的总和。
输出
Value of total : 30
Value of total : 40
限时特惠:本站持续每日更新海量各大内部创业课程,一年会员仅需要98元,全站资源免费下载
点击查看详情
站长微信:Jiucxh