Python Function Example: How to Define and Use a Function
Here's a basic example demonstrating how to define and use a function in Python:
# Define a function that takes in two numbers and returns their sum
def add_numbers(num1, num2):
return num1 + num2
# Use the function by calling it with two arguments
result = add_numbers(3, 4)
# Print the result of the function call
print(result) # Output: 7
In this code:
- We define a function named 'add_numbers' using the
defkeyword. It takes two parameters:num1andnum2. - Inside the function, we calculate the sum of
num1andnum2and use thereturnstatement to send the result back. - We call the
add_numbersfunction with the arguments3and4, storing the returned value in theresultvariable. - Finally, we print the value of
result, which is 7.
原文地址: https://www.cveoy.top/t/topic/nTJC 著作权归作者所有。请勿转载和采集!