Python Function
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
Defining a Function
You can define a function using the def
keyword, followed by the function name and a set of parentheses ()
. Optionally, you can add parameters inside the parentheses. The block of code within every function starts with a colon :
and is indented.
For example, the following function takes a string as parameter and prints it to the console:
def greet(name):
print("Hello, " + name)
Calling a Function
To call a function, you simply use the function name followed by a set of parentheses ()
and pass any required parameters. For example:
greet("John")
This will print “Hello, John” to the console.
Returning a Value
By default, functions return None
. However, you can use the return
statement to return a value from the function. For example:
def get_sum(a, b):
return a + b
result = get_sum(1, 2)
print(result) # 3
Optional Parameters
You can define default values for function parameters, which makes them optional. If a default value is provided for a parameter, the corresponding argument can be omitted from the function call. For example:
def greet(name, greeting="Hello"):
print(greeting + ", " + name)
greet("John") # Hello, John
greet("John", "Hi") # Hi, John
Variable-Length Arguments
Sometimes, you may need to define a function that can accept a variable number of arguments. In Python, this is done using the *args
and **kwargs
syntax.
*args
is used to pass a non-keyworded, variable-length argument list to the function. **kwargs
is used to pass a keyworded, variable-length argument list to the function. For example:
def print_info(name, *args, **kwargs):
print("Name:", name)
print("Arguments:", args)
print("Keyword arguments:", kwargs)
print_info("John", 1, 2, 3, job="developer", age=30)
This will print the following output:
Name: John
Arguments: (1, 2, 3)
Keyword arguments: {'job': 'developer', 'age': 30}