Python Functions
Functions are organized, reusable code segments that implement single or related functions. Functions improve the modularity of applications and code reuse. You have already used many built-in functions like print() and len(), and now you will learn how to create your own functions.
Defining Functions
- The function code block starts with the
defkeyword, followed by the function name and parentheses(). - Any arguments and variables passed in must be placed between the parentheses.
- The first line of the function can optionally use a docstring (document string) to add a description to the function.
- The function body starts with a colon
:and is indented. return [expression]ends the function and optionally returns a value to the caller. Areturnstatement without an expression is equivalent to returningNone.
Basic Syntax:
def function_name(parameters):
"""Function's docstring"""
# Function body
statement(s)
return [expression]Calling Functions
Defining a function only gives the function a name, specifies the parameters contained in the function, and the code block structure. After completing this basic structure of the function, you can execute it by calling from another function, or directly from the Python command prompt.
# Define a simple function
def greet():
"""Print a greeting."""
print("Hello, Python!")
# Call the function
greet() # Output: Hello, Python!Parameters
Functions can receive parameters, which are values passed to the function for internal use.
Positional Parameters
When calling a function, the passed values are assigned to parameters in order.
def greet_user(name):
"""Print a greeting to the specified user."""
print(f"Hello, {name}!")
greet_user("Alice") # Output: Hello, Alice!Keyword Parameters
You can also use key=value form to pass parameters, allowing you to ignore parameter order.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(animal_type="hamster", pet_name="Harry")
describe_pet(pet_name="Harry", animal_type="hamster") # Order doesn't matterDefault Parameters
When defining a function, you can specify a default value for a parameter. If the function is called without providing a value for that parameter, the default value will be used.
def describe_pet(pet_name, animal_type="dog"):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet("Willie") # Uses default value 'dog'
# Output: I have a dog named Willie.
describe_pet("Mitty", "cat") # Provides new value 'cat'
# Output: I have a cat named Mitty.Return Values
Functions can use the return statement to return a value to the caller. A function can return any type of value, including complex structures like lists and dictionaries.
def add(a, b):
"""Return the sum of two numbers."""
return a + b
result = add(5, 3)
print(result) # Output: 8A function can have no return statement, or return followed by no value. In this case, the function automatically returns None.
Returning Multiple Values
A function can return multiple values at once; these values will be packaged as a tuple.
def get_name_and_age():
name = "John"
age = 30
return name, age
# Receive return value
info = get_name_and_age()
print(info) # Output: ('John', 30)
# Use tuple unpacking to receive
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}") # Output: Name: John, Age: 30Variable Scope
- Local Variables: Variables defined inside a function can only be accessed within that function.
- Global Variables: Variables defined outside a function can be accessed anywhere in the program (including inside functions).
global_var = "I am global"
def my_function():
local_var = "I am local"
print(global_var) # Can access global variables
print(local_var)
my_function()
# print(local_var) # This will raise NameError because local variables cannot be accessed outside the function