Introduction To Python Functions
- Read
- Discuss
In Python, a function is a block of code that can be reused multiple times throughout a program. Functions are defined using the def keyword, followed by the function name and a set of parentheses.
The parentheses may contain parameters and variables that will be passed into the function when it is called. Here is an example of a simple function that takes no parameters and returns a string:
def say_hello():
return "Hello, World!"
print(say_hello()) # Output: "Hello, World!"
Functions can also accept parameters, which allow the function to accept input and process it in some way. The following example shows a function that takes a single parameter, name, and returns a personalized greeting:
def say_hello(name):
return f"Hello, {name}!"
print(say_hello("John")) # Output: "Hello, John!"
Functions can also have default values for parameters, which means that if a value is not provided for that parameter when the function is called, the default value will be used instead. The following example shows a function that has a default value for its greeting parameter:
def say_hello(name, greeting = "Hello"):
return f"{greeting}, {name}!"
print(say_hello("John")) # Output: "Hello, John!"
print(say_hello("John", "Hi")) # Output: "Hi, John!"
This will output:
Hello, John!
Hi, John!
You can also use the *args and **kwargs syntax to define functions that take a variable number of arguments. *args allows the function to accept any number of positional arguments, while **kwargs allows the function to accept any number of keyword arguments. Here is an example of a function that uses *args and **kwargs:
def print_args(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
print_args(1, 2, 3, name="John", age=25)
This will output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'John', 'age': 25}
Functions can also return multiple values using tuple unpacking:
def get_min_max(numbers):
return min(numbers), max(numbers)
minimum, maximum = get_min_max([3, 1, 4, 2, 5])
print(minimum, maximum)
This will output:
1 5
In this tutorial, I’ve covered the basics of creating and using functions in Python. I’ve shown how to define a function, how to accept and pass parameters, how to use default values, how to use *args and **kwargs, and how to return multiple values using tuple unpacking.
Leave a Reply
You must be logged in to post a comment.